Do php autoload functions make an object available to any part of the site in the same session, even in different sub directories?

1

I intend to make my code cleaner and so avoid using include or include_once all top of page. I would not like to use frameworks that already do this work as laravel for example. I want to create the "from the scratch" function.

So here we have 2 distinct ways to use autoload functions to call a class when trying to instantiate an object.

spl_autoload_register(function ($class_name) {              
    include './class/'.$class_name . '.php';
});

================== ou ========================

function __autoload($className) {
    $className = str_replace("..","", $className);
    require_once ("./class/$className.php");
}

I'm using the function on page index.php . My question is whether there is any sub-level constraint for it to work. That is, if a class is called in a file.php ($myObj=new myclass();) file within the dir1/dir2/dir3/file.php directory, would it still recognize the path to root/class/myclass.php ? Is there a limit?

    
asked by anonymous 27.04.2016 / 19:47

1 answer

1

I recommend that you use autoload in the composer, which in addition to light it works well with namespaces.

But answering your question, when you concatenate the file path, puts the dirname(__FILE__) function in front of it, which will return the autoload folder. From this folder just go to the class folder.

    
27.04.2016 / 20:57