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

Asked

Viewed 272 times

1

I intend to make my code cleaner and therefore avoid using include or include_once all page start. I would not like to use frameworks that already do this work as Windows for example. I want to create the function "from the Scratch".

So here are 2 different 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 the page index.php. My question is whether there is a sublevel constraint for it to work. That is, if a class is called in a file file.php ($myObj=new myclass();) inside the directory dir1/dir2/dir3/file.php she would continue to recognize the path until root/class/myclass.php? Is there any limit ?

  • Thank you for the explanation of how to use, also would like to know.

1 answer

1


I recommend that you use autoload in Composer, which besides lightweight it works well with namespaces.

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

  • Like I said, I’ve been wanting to do something from scratch. I didn’t want to use either Laravael or Composer. So it means that if I declare the function on the index.php page, pass the path of the class directory relative to index.php and call a class 2 or 3 levels below the index it would not work?

  • Yes it will work because it takes the folder of the file that has the function dirname(__FILE__). Independent of where it began to be executed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.