Home  >  Article  >  Backend Development  >  What is the function of php call magic method

What is the function of php call magic method

青灯夜游
青灯夜游Original
2021-09-03 11:44:372147browse

php The "__call()" magic method will be called when calling a method that does not exist or is inaccessible. Its function is to allow the program to continue executing and avoid running when the called method does not exist or is inaccessible. An error occurs that causes the program to terminate.

What is the function of php call magic method

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In object-oriented programming, PHP provides an A series of magic methods, these magic methods provide a lot of convenience for programming, and their role in PHP is very important. Magic methods in PHP usually start with __ (two underscores) and do not need to be explicitly called but are automatically called under certain conditions.

Among them, the __call() or __callStatic() method is designed to achieve overloading. Let’s introduce the __call method to you.

php __call magic method

The __call() method is called when an inaccessible or non-existent method in a class is called. The syntax format of this method is as follows:

public function __call($name, $arguments){
    ... ... ;
}

where $name is the name of the method to be called, and $arguments is an array of parameters passed to $name.

When the called method does not exist, the __call() method will be automatically called, and the program will continue to execute, thus avoiding program termination caused by an error when the calling method does not exist.

[Example] The following uses a simple example to demonstrate the use of the __call() method.

<?php
header("Content-type:text/html;charset=utf-8");
class Website{
    public function say(){
        echo &#39;Welcome PHP中文网!<br>&#39;;
    }
    public function __call($name, $arguments){
        echo &#39;你所调用的方法:&#39;.$name;
        if(!empty($arguments)){
            echo &#39;【以及参数:&#39;;
            print_r($arguments);
            echo &#39;】&#39;;
        }
        echo &#39; 不存在!<br>&#39;;
    }
}
$obj = new Website();
$obj -> say();
$obj -> url(&#39;https://www.php.cn/&#39;);
$obj -> title();
?>

The running results are as follows:

What is the function of php call magic method

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of What is the function of php call magic method. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn