353 of 410 menu

The __callStatic Method

The __callStatic method is a magic method in PHP that is automatically called when attempting to call a non-existent or inaccessible static method. Its first parameter is the name of the called method, and the second is an array of passed arguments.

Syntax

public static function __callStatic(string $name, array $arguments);

Example

Let's create a class with the __callStatic method and try to call a non-existent static method:

<?php class MyClass { public static function __callStatic($name, $args) { echo "Called static method '$name' with arguments: "; print_r($args); } } MyClass::nonExistentMethod(1, 2, 3); ?>

Code execution result:

Called static method 'nonExistentMethod' with arguments: [1, 2, 3]

Example

Let's implement a simple facade for creating objects of different types:

<?php class Factory { public static function __callStatic($name, $args) { if (strpos($name, 'create') === 0) { $className = substr($name, 6); return new $className(...$args); } throw new Exception("Method $name not found"); } } class User {} $user = Factory::createUser(); var_dump($user instanceof User); ?>

Code execution result:

true

See Also

  • the __call method,
    which intercepts calls to non-existent object methods
  • the __get method,
    which intercepts access to non-existent properties
byenru