I had spl_autoload_register working fine but then I decided to add some namespacing to bring in PSR2 compliance and can't seem to get it working.
Directory strcuture:
-index.php
-classes/
-Class1.class.php
-Class2.class.php
-Class3.class.php
Each class starts with:
namespace Foo;
Class ClassX {
Index.php:
<?php
spl_autoload_register(function($class) {
include 'classes/' . $class . '.class.php';
});
$myObj = new Class1();
echo $myObj->doSomething();
This products an error Fatal error: Class 'Class1' not found in /var/www/myApp/index.php on line X
My first thought was that I need to use a namespace with my instantiation, so I changed index.php
to:
$myObj = new Foo\Class1();
However, then I get
Warning: include(classes/Foo\Class1.class.php): failed to open stream: No such file or directory in /var/www/myApp/index.php on line 6
If I do manual includes everything works fine,include 'classes/Class1.class.php';
and so on.
A namespace is a hierarchically labeled code block holding a regular PHP code. A namespace can contain valid PHP code. Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants. Namespaces are declared using the namespace keyword.
If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.
Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.
In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.
So the problem was that the $class
being returned to spl_autoload_register
was the namespace\class name, with the backslash intact. So when I instantiated a new object:
$myObj = new Foo\Class1();
The include path became /var/www/myApp/classes/Foo\Class1.php
, the backslash breaking the path.
I implemented this to fix the backslash, and it now works, although I do not know why this is necessary.
spl_autoload_register(function($class) {
include 'classes/' . str_replace('\\', '/', $class) . '.class.php';
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With