PHP __call() Magic Method (original) (raw)

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 #

When you call a method of an object, if the method does not exist or is private, PHP will call the __call() method automatically.

The following shows the syntax of the __call() method:

public __call ( string <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>n</mi><mi>a</mi><mi>m</mi><mi>e</mi><mo separator="true">,</mo><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><mi>y</mi></mrow><annotation encoding="application/x-tex">name , array </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.625em;vertical-align:-0.1944em;"></span><span class="mord mathnormal">nam</span><span class="mord mathnormal">e</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">rr</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span></span></span></span>arguments ) : mixedCode language: PHP (php)

The __call() method accepts two arguments:

The __call() method is useful when you want to create a wrapper class that wraps existing API.

Suppose that you want to develop the Str class that wraps existing string functions such as strlen(), strtoupp() and strtolower().

Typically, you can define these methods explicitly like length, upper, lower, … Doing so would take time. Instead, you can use utilize the __call() magic method to make the code more concise.

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'
            'substring' => 'substr'
      // map more method to functions
];

public function __construct(string $s)
{
 <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>t</mi><mi>h</mi><mi>i</mi><mi>s</mi><mo>−</mo><mo>&gt;</mo><mi>s</mi><mo>=</mo></mrow><annotation encoding="application/x-tex">this-&gt;s = </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.7778em;vertical-align:-0.0833em;"></span><span class="mord mathnormal">t</span><span class="mord mathnormal">hi</span><span class="mord mathnormal">s</span><span class="mord">−</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">&gt;</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.4306em;"></span><span class="mord mathnormal">s</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span></span></span></span>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: PHP (php)

How it works.

The $functions property store the mapping between the methods and built-in string functions.

For example, if you call the length() method on a string object, the __call() method will call the strlen() function.

When you call a method on an instance 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() . '
'; // HELLO, WORLD! echo $s->lower() . '
'; // hello, world! echo $s->length() . '
'; // 13`Code language: PHP (php)

Try it

Output:

HELLO, WORLD! hello, world! 13Code language: PHP (php)

In this example, the $args of the __call() method is an empty string.

The following example shows how to call the substring method:

`<?php

require 'Str.php';

$s = new Str('phptutorial.net'); echo $s->substring(0,11);`Code language: PHP (php)

Try it

Output:

phptutorialCode language: PHP (php)

In this example, the $args argument of the __call() method is [0,11].

Summary #

Did you find this tutorial useful?