Home >Backend Development >PHP Problem >Which category does php's __call function belong to?

Which category does php's __call function belong to?

(*-*)浩
(*-*)浩Original
2019-10-09 11:54:202595browse

php's __call() function is a magic function. The so-called PHP magic function simply means that it has a specific name in PHP - all starting with two underscores, and the PHP interpreter will A method to automatically find and run when a certain timing is reached.

Which category does php's __call function belong to?

When we call an inaccessible member method, the __call magic method will be called.

No The accessed member method refers to (1. The member method does not exist, 2. The member method is protected or private) (Recommended learning: PHP Video Tutorial)

We just hope that in Directly call inaccessible member methods (private, protected) from outside the class.

Case Description

<?php
    header(&#39;content-type:text/html;charset=utf-8&#39;);
    //__call魔术方法

     class Monk{
        public $name;
        protected $hobby;

        public function __construct($name, $hobby){
            $this->name = $name;
            $this->hobby = $hobby;
        }
        
        //输出该对象的信息
        public function showInfo(){
            
            echo &#39;<br> 名字是 &#39; . $this->name;
            foreach($this->hobby as $hobby){
                echo &#39;<br> 爱好有 &#39; . $hobby;
            }
        }

        //会做算术题, 保护的
        protected function getSum($num1, $num2){
            
            return $num1 + $num2;
        }

        //编写这个__call魔术方法, __call 魔术方法会接收到两个参数
        /*
            @param $method_name 就是函数名
            @param $parameters 就是参数,类型是array
        */
        public function __call($method_name, $parameters){
            
//            echo &#39;<br> method_name = &#39; . $method_name;
//            echo &#39;<br> $parameters <br>&#39;;
//            var_dump($parameters);
            
            //判断 $this 中是否有  $method_name 函数,有就返回true,否则返回false
            if(method_exists($this, $method_name)){

                return $this->$method_name($parameters[0], $parameters[1]);
            }else{
                return &#39;没有你要调用的函数&#39;;
            }
            
        }
     }

     $monk = new Monk(&#39;济公&#39;, array(&#39;no1&#39;=>&#39;腾云驾雾&#39;, &#39;no2&#39;=>&#39;喝酒&#39;));

     $monk->showInfo();

     //当我们直接调用 protected 方法时,就会触发 __call 魔术方法
     echo &#39;<br> 结果是&#39; . $monk->getSum(100, 200);

The above is the detailed content of Which category does php's __call function belong to?. 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