PHP 8.4.24 Released!

Voting

: max(five, three)?
(Example: nine)

The Note You're Voting On

rangel
17 years ago
The term "autoload" mentioned here shall not be confused with __autoload function to autoload objects. Regarding the __autoload and namespaces' resolution I'd like to share the following experience:

->Say you have the following directory structure:

- root
      | - loader.php 
      | - ns
             | - foo.php

->foo.php

<?php
namespace ns;
class foo
{
    public $say;
    
    public function __construct()
    {
        $this->say = "bar";
    }
    
}
?>

-> loader.php

<?php
//GLOBAL SPACE <--
function __autoload($c)
{
    require_once $c . ".php";
}

class foo extends ns\foo // ns\foo is loaded here
{
    public function __construct()
    {
        parent::__construct();
        echo "<br />foo" . $this->say;
    }
}
$a = new ns\foo(); // ns\foo also loads ns/foo.php just fine here.
echo $a->say;   // prints bar as expected.
$b = new foo;  // prints foobar just fine.
?>

If you keep your directory/file matching namespace/class consistence the object __autoload works fine.
But... if you try to give loader.php a namespace you'll obviously get fatal errors. 
My sample is just 1 level dir, but I've tested with a very complex and deeper structure. Hope anybody finds this useful.

Cheers!

<< Back to user notes page

To Top