Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP namespacing and spl_autoload_register

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.

like image 224
diplosaurus Avatar asked Mar 19 '14 02:03

diplosaurus


People also ask

What is Namespacing in PHP?

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.

What is Spl_autoload_register?

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.

What is the use of namespace and use in PHP?

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.

Does PHP support namespace?

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.


1 Answers

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';
});
like image 90
diplosaurus Avatar answered Sep 21 '22 12:09

diplosaurus