Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

__call() Method

__call() is a magic method: it is called when a method cannot be accessed, either because it doesn’t exist, or because its visibility prevents it.

That way, it is possible to dynamically create methods, without hardcoding them.

The __call() method receives the name of the target-method, and a list of arguments, as an array.

The __call() method has a related version for static methods, called __callStatic().

<?php

    class Elephpant {
        private $values = ['a' => 1,
                           'b' => 2,
                           ];

        // Checks the dictionary, or return 0
        function __call($name, $args) {
            if (method_exists($this, $name)) {
                return $this->$name(...$args);
            }
            
            return 0;
        }
    }

?>

Documentation

See Also