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?
3 Answers
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!
2 Comments
The __callStatic() is called everytime you call not existing static method of a class.
1 Comment
Could __callStatic() be the method you are referring to? I just found this in the PHP Manual:
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.methods
Perhaps not, though, since it seems to be a magic method to handle undefined static method calls...