Summary: in this tutorial, you will learn about the PHP __call()
magic method and how to use it to wrap existing functions.
Introduction to the PHP __call magic method
The __call()
method is invoked automatically when a non-existing method or inaccessible method is called. The following shows the syntax of the __call()
method:
public __call ( string $name , array $arguments ) : mixed
Code language: PHP (php)
The __call()
method accepts two arguments:
$name
is the name of the method that is being called by the object.$arguments
is an array of arguments passed to the method call.
The __call()
method is useful when you want to create a wrapper class that wraps the existing API.
PHP __call() magic method example
Suppose that you want to develop the Str
class that wraps existing string functions such as strlen()
, strtoupp()
, strtolower()
, etc.
Typically, you can define the method explicitly like length, upper, lower, … But you can use utilize the __call()
magic method to make the code shorter.
The following defines the Str class that uses the __call()
magic method:
<?php
class Str
{
private $s = '';
private $functions = [
'length' => 'strlen',
'upper' => 'strtoupper',
'lower' => 'strtolower'
// map more method to functions
];
public function __construct(string $s)
{
$this->s = $s;
}
public function __call($method, $args)
{
if (!in_array($method, array_keys($this->functions))) {
throw new BadMethodCallException();
}
array_unshift($args, $this->s);
return call_user_func_array($this->functions[$method], $args);
}
}
Code language: HTML, XML (xml)
How it works.
The $functions
property store the mapping between the methods and built-in string function. For example, if you call the length()
method, the __call()
method will call the strlen()
function.
When you call a method on an object of the Str class and that method doesn’t exist e.g., length()
, PHP will invoke the __call()
method.
The __call()
method will raise a BadMethodCallException
if the method is not supported. Otherwise, it’ll add the string to the argument list before calling the corresponding function.
The following shows how to uses the Str
class:
<?php
require 'Str.php';
$s = new Str('Hello, World!');
echo $s->upper() . '<br>'; // HELLO, WORLD!
echo $s->lower() . '<br>'; // hello, world!
echo $s->length() . '<br>'; // 13
Code language: HTML, XML (xml)
Output:
HELLO, WORLD!
hello, world!
13
Summary
- The
__call()
method is invoked automatically when a nonexisting method or an inaccessible method is called. - Use the
__call()
method to wrap existing API into a class.