Blogger Information
Blog 34
fans 0
comment 0
visits 33683
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
魔术方法:__call()和__callStatic()
Serendipity-Ling
Original
1249 people have browsed it
<?php
/**
 * 魔术方法:__call()和__callStatic()
 * __call($name, $arguments):调用类中不存在的动态方法,自动调用
 * __callStatic($name, $arguments):调用类中不存在的静态方法,自动调用
 * 以上二个魔术方法实现了方法的重载
 */
require 'call_back.php';
class Call_1
{
    //调用动态方法
    public function __call($name, $arguments)
    {
        //打印出方法名和参数,参数是在数组$arguments中
//        return '<p>方法名:'.$name.',参数是:('.implode(',',$arguments).')</p>';
        //跨类调用方法
        //call_user_func_array($method,$array_param);
//        print_r($arguments);
        //call_user_func_array([对象,'方法名',参数数组])
       return call_user_func_array([(new Call_2()),$name],$arguments);
    }
    //调用静态方法
    public static function __callStatic($name, $arguments)
    {
        return call_user_func_array(['Call_2',$name],$arguments);
    }
}
//动态
$obj = new Call_1();
echo $obj->hello(1,2,3);//输出6,成功调用了Call_2类中的方法
echo '<hr>';
//静态
echo $obj->add(1,100);//结果输出5050,成功调用了Call_2类中的add()方法

调用的类

<?php
/**
 * 调用文件
 */
class Call_2
{
    private static $c;
    public function hello($arg1,$arg2,$arg3)
    {
            return $arg1+$arg2+$arg3;
    }
    //静态方法
    public static function add($a,$b)
    {
        for ($i=$a; $i<=$b;$i++)
        {
            self::$c+=$i;
        }
        return self::$c;
    }
}


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post