tags:

views:

498

answers:

2

I get this error when I try to use autoload and namespaces:

Fatal error: Class 'Class1' not found in /usr/local/www/apache22/data/public/php5.3/test.php on line 10

Can anyone tell me what I am doing wrong?

Here is my code:

[root@data /usr/local/www/data/public/php5.3]# ls -l
total 8
-rw-r--r--  1 root  wheel  160 Dec  1 23:46 Class1.php
-rw-r--r--  1 root  wheel  122 Dec  1 23:46 test.php
[root@data /usr/local/www/data/public/php5.3]# cat Class1.php
<?php

namespace Person\Barnes\David
{
    class Class1
    {
        public function __construct()
        {
            echo __CLASS__;
        }
    }
}

?>
[root@data /usr/local/www/data/public/php5.3]# cat test.php
<?php

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

use Person\Barnes\David;

$class = new Class1();

?>
[root@data /usr/local/www/data/public/php5.3]#
A: 

Your __autoload function will receive the full class-name, including the namespace name.

This means, in your case, the __autoload function will receive 'Person\Barnes\David\Class1', and not only 'Class1'.

So, you have to modify your autoloading code, to deal with that kind of "more-complicated" name ; a solution often used is to organize your files using one level of directory per "level" of namespaces, and, when autoloading, replace '\' in the namespace name by DIRECTORY_SEPARATOR.

Pascal MARTIN
This is not what I found. When I did put the statement die($class); in the __autoload function, it printed out 'Class1"', not 'Person\Barnes\David\Class1'
David Barnes
+4  A: 

Class1 is not in the global scope.

See below for a working example:

<?php

function __autoload($class)
{
    $parts = explode('\\', $class);
    require end($parts) . '.php';
}

use Person\Barnes\David as MyPerson;

$class = new MyPerson\Class1();

Edit (2009-12-14):

Just to clarify, my usage of "use ... as" was to simplify the example.

The alternative was the following:

use Person\Barnes\David;

$class = new Person\Barnes\David\Class1();
enbuyukfener
Thanks, I didn't realize I had to to "use ... as".
David Barnes
No worries David. Also see the edit for a clarification.
enbuyukfener