Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoload namespaces based on directory structure

According to the top comment on the PHP page spl_autoload_register( ) :

Good news for PHP 5.3 users with namespaced classes:

When you create a subfolder structure matching the namespaces of the >containing classes, you will never even have to define an autoloader.

<?php
    spl_autoload_extensions(".php"); // comma-separated list
    spl_autoload_register();
?>

However, when I have the following structure:

* classes/someclass.php

* index.php

Where someclass.php contains the following:

<?php
    class someclass {
        function __construct( ) {
            echo 'It works!';
        }
    }
?>

and index.php contains:

<?php
    spl_autoload_extensions(".php");
    spl_autoload_register();

    new classes\someclass;
?>

Then I get the following error:

Fatal error: spl_autoload(): Class classes\someclass could not be loaded

Am I getting this wrong? How can I make this work?

From the comments

This doesn't work either for the class:

<?php
    namespace classes;
    class someclass {
        function __construct( ) {
            echo 'It works!';
        }
    }
?>
like image 575
SAz Avatar asked Jun 01 '15 09:06

SAz


1 Answers

In your someclass.php file you must define the namespace at the begginning.

<?php 
namespace classes;
like image 67
m4t1t0 Avatar answered Sep 28 '22 07:09

m4t1t0