PHP __call Magic Method With Example

The PHP __call is a method which invoked automatically when there is an inaccessible or non-existing method were called.

In this article, we will talk about PHP __call() function in a detailed explanation as well as example programs that could be helpful to your future projects. This topic is a continuation of the previous topic, entitled PHP Usort.

What is __call() in PHP?

In PHP, __call is a built-in PHP function that is mainly used to __get() the class functions to class variables.

For instance, if you want to call the bark() from the object class dog, the PHP could not find the function construct and then they will check if you defined a PHP call function.

Syntax

public __call ( string $name , array $arguments ) : mixed

Parameter values

ParameterDescription
$nameThis parameter is the name of the private (method) which is being called by the object.
$argumentsThis parameter is an argument of the return array which has been passed on the method return call user func array.
PHP __call

Example

<?php
    class dog {
        public $Name;

        public function bark(){
            print "Woof!\n";
        }
        
        public function __call($function, $args){
            $args = implode(', ', $args);
            print "Call to $function() with args '$args' failed!\n";
        }
    }

    $poppy = new dog;
    $poppy->all("charlie", "delta", "samantha");
?>

Output

Call to all() with args 'charlie, delta, samantha' failed!

Summary

In summary, you have learned about PHP __call function. This article also discussed what is __call() in PHP class, and an example program that can be helpful.

I hope this lesson has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.

Leave a Comment