Reputation: 647
I get this example from http://www.php.net/manual/ru/function.spl-autoload.php#92767
But this causes an error *Fatal error: spl_autoload() [function.spl-autoload]: Class space could not be loaded in C:\my_projects\site.local\www\index.php on line 18*
/index.php
// Your custom class dir
define('CLASS_DIR', 'oop/classes');
// Add your class dir to include path
set_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);
// You can use this trick to make autoloader look for commonly used "My.class.php" type filenames
spl_autoload_extensions('.class.php');
// Use default autoload implementation
spl_autoload_register();
new space/my;
/oop/classes/space/my.class.php
namespace space;
class my{
public function __construct{
var_dump('space class was here!');
}
}
I know about PSR-0, but in my case I need to understand how built function works
Upvotes: 0
Views: 1910
Reputation: 197564
The following line of code is likely to be a syntax error because you did not use the language syntax as you might have thought:
new space/my;
Let's take it apart what we have here:
new
- the new
keyword, we use it to instantiate a new object.space
- the name of the class, here the string "space"
./
- the division operator. my
- the (undefined?) constant my
which will result into the string "my"
if undefined.Because of that just being so (that is the language), PHP naturally tries to instantiate the class space
and then tries to devide it with the string "my"
. Example:
$object = new space;
define('my', 0);
$result = $object / my;
Because of you using autoloading and the class space
non-existence you see the fatal error.
So strictly spoken the syntax error is not in PHP but by using the wrong syntax (here: /
instead of \
which is the correct symbol to separate namespaces).
Hope this is helpful. Take care that PHP has loose typing so an existing class that could have been instantiated would have produced probably a division by zero warning.
Debugging spl_autoload_register
: As this is an internal function when used with no autoloader callback function, you can extend it with the following for debugging purposes:
spl_autoload_register(funcion($class) {
echo 'Autoloading class: ', var_dump($class), "\n";
return spl_autoload($class);
});
Also you might want to add your extension(s) instead of overwriting the existing ones:
($current = spl_autoload_extensions()) && $current .= ',';
spl_autoload_extensions($current . '.class.php');
# .inc,.php,.class.php
Upvotes: 2
Reputation: 160833
new space/my;
should be
new space\my;
Note: you missed ()
of the __construct
in my.class.php
Upvotes: 3