The __callStatic() magic method works as the same way as __call() magic method with the only difference is it works only with static methods.
Please note that __callStatic()
magic method is a static function and should be called statically.
Simple Example
class DevPeel
{
public static function __callStatic($name,$arguments){
var_dump($name,$arguments);
}
}
DevPeel::someMethod('dev',100);
You can notice here, it’s same as __call() magic method but used statically. It’ll output the following:
string(10) "someMethod"
array(2) {
[0]=>
string(3) "dev"
[1]=>
int(100)
}
Another Example (Facade Technique)
Again taking inspiration from Laravel, we’ve an Auth facade and we require to login attempt using our username & password. We can achieve this using the following simple technique:
class Auth
{
public static function attempt($username,$password){
var_dump('attempt');
}
}
Auth::attempt('usamamuener','secret');
Now let’s see a more detailed approach of doing the same using __callStatic()
magic method.
class AuthService
{
public function attempt($username,$password){
var_dump('attempt',$username,$password);
}
}
class Auth
{
public static function service(){
return new AuthService();
}
public static function __callStatic($name,$arguments){
return self::service()->{$name}(...$arguments);
}
}
Auth::attempt('usamamuneer','secret');
Let’s do some more refactoring.
class AuthService
{
public function attempt($username,$password){
var_dump('attempt',$username,$password);
}
}
abstract class Facade
{
public static function __callStatic($name,$arguments){
return static::service()->{$name}(...$arguments);
}
}
class Auth extends Facade
{
public static function service(){
return new AuthService();
}
}
Auth::attempt('usamamuneer','secret');
Now every time we add a new Facade, we’ll extend the Facade class and everything will works exactly the same.