Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the PHP autoloader function also work with static method calls?

Tags:

I slightly remember that autoload worked with the new statement. Now how about when I have several utility classes and I want to autoload these? And I only use static methods?

Like:

MathGuru::calculateFoo($bar); 

Would autoload load MathGuru here? Or must I include it manually?

like image 692
openfrog Avatar asked Jan 11 '10 19:01

openfrog


People also ask

How does PHP autoloader works?

The PHP Autoloader searches recursively in defined directories for class, trait and interface definitions. Without any further configuration the directory in which the requiring file resides will be used as default class path. File names don't need to obey any convention. All files are searched for class definitions.

Can static function call non-static function PHP?

In PHP 5, calling non-static methods statically generates an E_STRICT warning. In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. See Static methods (php.net) for details. In the following example, the method foo() is called as dynamic while actually it is static.

Can we use this in static method PHP?

You can't use $this inside a static function, because static functions are independent of any instantiated object. Try making the function not static. Edit: By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.

Why not use static methods PHP?

It's generally a bad idea to depend on static methods because they make substitution (and therefore specialising or testing) difficult. It looks like what you have is 10 independent classes that all inherit from the same interface. But without explaining what those functions do, its impossible to say how to improve.


1 Answers

The autoloading mechanism works exactly the same way with static classes that it does with non-static one :

  • The autoload function/method you registered will be called
  • It'll receive the name of the class
  • And it'll have to require/include the necessary PHP code


Actually, the autoloader doesn't even have to "know" if it is called to load a static or a dynamic class, as its role is to load the PHP code that contains the class' definition -- and not instantiate it or anything.

like image 115
Pascal MARTIN Avatar answered Nov 14 '22 08:11

Pascal MARTIN