A few months ago, I have read about a PHP function that is called every time a static method is called, similar to the __construct
function that is called when an instance of class is instantiated. However, I can't seem to find what function takes care of this functionality in PHP. Is there such a function?
A static constructor is just a method the developer can define on a class which can be used to initialise any static properties, or to perform any actions that only need to be performed only once for the given class. The method is only called once as the class is needed.
A static constructor doesn't take access modifiers or have parameters. A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR).
Here comes the call of static method with static keyword. In case there is no overridden function then it will call the function within the class as self keyword does. If the function is overridden then the static keyword will call the overridden function in the derived class.
New static: The static is a keyword in PHP. Static in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on. The most common usage of static is for defining static methods.
You can play with __callStatic() and do something like this:
class testObj {
public function __construct() {
}
public static function __callStatic($name, $arguments) {
$name = substr($name, 1);
if(method_exists("testObj", $name)) {
echo "Calling static method '$name'<br/>";
/**
* You can write here any code you want to be run
* before a static method is called
*/
call_user_func_array(array("testObj", $name), $arguments);
}
}
static public function test($n) {
echo "n * n = " . ($n * $n);
}
}
/**
* This will go through the static 'constructor' and then call the method
*/
testObj::_test(20);
/**
* This will go directly to the method
*/
testObj::test(20);
Using this code any method that is preceded by '_' will run the static 'constructor' first.
This is just a basic example, but you can use __callStatic
however it works better for you.
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With