Domanda

I'm using this method to load classes:

spl_autoload_register(function($class) {
    require_once 'classes/' . $class . '.php';
});

There are still some things about that functions that I'm struggling to understand.

As I've understood, whenever I wil create an object instance, it will trigger the function and load the objcet's class.

So, if i was to do something like:

$myObj = new myObj();

The function would catch this decleration, and will require_once 'classes/myObj.php'.

What happens if i create another instance? for example:

$myObj1 = new myObj();
$myObj2 = new myObj();

It will trigger the function twice? or it's noticing that it's the same class, so it doesn't delcare that twice? In any case, that's why I used require_once so I won't get an overload. But still, I would like to know what it actually does.

One more thing, why when I'm doing code like this:

echo someOtherClass::getDesc();

The function still recognizes this as a class decleration and then requires the file classes/someOtherClass.php. Why is that happening? I haven't declared a new object, infact, I got NO object that is an instance of someOtherClass. Does that mean whenever I'm using an object function it will try to include the class? or whenver I use a static function maybe?

Thanks in advance!

È stato utile?

Soluzione

Basically upon encountering a class that is not defined it will call the functions registered in the autoload stack one by one checking after each call whether the class is defined, if it is it stops calling loaders and returns to script execution.

Therefore it is effectively same as require_once, and yes invocation of static method of undeclared class triggers the autoload.

You can think of autoload as of an exception "Class not declared" handler, it is meant to fix it so your script can continue.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top