In this lesson, we’re going to learn and get familiar with PHP __callStatic() Magic Method tutorial along with example and explanation.
PHP Magic Method: __callStatic() Definition
__callStatic is one of the magic methods in PHP programming language that will be called/running when there’s a static function of a class is being called, however that static function is not defined yet.
PHP Magic Method: __callStatic Declaration
__callStatic PHP magic method is declared with the following format:
__callStatic ( string $name , array $arguments ) : mixed
The declaration format above tells us that the __callStatic method is storing a string data type as its first argument, and store array data type as its second argument. This is a mixed type function.
PHP Magic Method: __callStatic Example
__callStatic magic method as it’s already explained is a magic method that will be called when you tried to call a non-existing static function of a class.
class Car
{
public static function drive()
{
echo "Someone's driving the car";
}
function __callStatic($function, $args)
{
$args = implode(', ', $args);
print "Call to $function() with args '$args' failed!\\n";
}
}
Pada class di atas kita mendefinisikan class bernama Car yang mana hanya memiliki satu buah function yakni drive()
. Jika kita membuat obyek dari class tersebut dan memanggil static function drive yang memang sudah ada, seperti berikut:
In the class above we defined a class named “Car” which has only one static function drive()
. If we create an instance from the Car class and call the existing static function, like the following:
$rangeRover = new Car();
$rangeRover::drive();
The PHP interpreter will return the following:
Namun apabila kita membuat sebuah obyek dari class tersebut dan memanggil static function yang belum ada atau belum didefinisikan, seperti contoh berikut:
However, if we instantiate an object from that class and call a static function that’s not existing yet, like the following code example:
$rangeRover = new Car();
$rangeRover::fly();
The PHP interpreter will give us the following result:
As a conclusion, the _call magic method is designed to provide a default code statement when there’s a non-existing function being called, and the _callStatic magic method is designed to provide a default code statement when there’s a non-existing static function being called.
Both _call
and _callStatic
methods are the magic methods provided by PHP to avoid the interpreter throw an error statement when a non-existing function/static function is being called. Instead, the interpreter will return the code statement that you’ve defined in those magic methods.
Reference: callStatic – PHP.net
No comments yet
Wanna write a response?
You have to login before write a comment to this post.