Michael Mikhjian
Michael Mikhjian

Reputation: 2794

PHP namespace and global autoload single file

This is an experiment with PHP namespaces / autoload in a single file.

namespace trust;

class trust_network{        
    public function __construct(){      
        print "SUP";
    }
}

namespace trust2;

$trust = new \trust\trust_network(); $do = new \test();

function __autoload($class){
    require($class.".php");     
    print $class;
}

So under namespace trust2, I'm calling "\test" - aka I'd like to autoload that class from an external file on a global base. What I wrote does not work. I know that I've got __autoload under a namespace, but how do I declare that on a global basis? Can't include before namespace declaration.

Upvotes: 1

Views: 920

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

Autoload is usually so that you can put one class per file. Therefore, you should have the following layout

/index.php

function __autoload($class){
    // You may need to convert backslashes in $class to forward slashes 
    // and strip the first slash, we'll leave the
    require($class.".php");
    // debug-only:  print $class;
}
// Calling new here triggers __autoload to be called
$trust = new \trust\trust_network();
$do = new \test();

/trust/trust_network.php

namespace trust;

class trust_network{        
    public function __construct(){      
        print "TRUST_NETWORK";
    }
}

/test.php

class test() {
    public function __construct(){      
        print "TEST";
    }
}

Note that you should use spl_autoload_register instead since it allows multiple systems to hook in their own autoload behavior. As of PHP 5.3, you can do the following

spl_autoload_register(function ($class) {
    require($class.".php");
});

Upvotes: 2

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

For multiple namespaces in one file you should use the curly bracket syntax:

namespace n1 {
...
}
namespace n2 {
...
}
namespace {
...
}

In the last block you can declare functions in the global namespace. Reference: http://www.php.net/manual/en/language.namespaces.definitionmultiple.php

Upvotes: 3

Related Questions