Blogger Information
Blog 30
fans 0
comment 0
visits 22491
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
9.4方法重载与call_user_func_array()
归宿的博客
Original
995 people have browsed it
  1. 方法重载与call_user_func_array()

1)方法重载:

class Test
{
    //普通方法的重载(如果没有__call方法,就不能在外部访问私有方法)
    public function __call($name, $arguments)
    {
//        return $name; //方法名称
//        return $arguments;
        $arrs = implode(',',$arguments);
        return '方法名:'.$name.'<br>参数:'.$arrs;
    }

    //创建一个私有方法
    private function select()
    {
        return __METHOD__;
    }

    //静态方法的重载
    public static function __callStatic($name, $arguments)
    {
        $arrs = implode(',',$arguments);
        return '方法名:'.$name.'<br>参数:'.$arrs;
    }

}
//实例化
$test = new Test;
//访问一个不存在的非静态/普通/动态方法
//echo $test->show();
print_r($test->show('合肥','杭州'));

echo $test->select('staff','id,name,age').'<hr>';

//从类外部访问一个不存在的静态方法
echo Test::assign('html,css,php');

2) call_user_func_array():

//场景一:执行回调函数
//计算两个整数之和
echo call_user_func_array(function($m,$n){return $m+$n;},[10,20]).'<hr>';

//场景二:执行对象方法
class Hello1
{
    public function add($m,$n)
    {
        return $m + $n;
    }
}
//call_user_func_array([对象,'方法'],[参数数组])
//$obj = new Hello1();
//$method = 'add';
//$args = [30,50];
//echo call_user_func_array([$obj,$method],$args),'<br>';
//可以简写:
echo call_user_func_array([(new Hello1()),'add'],[35,40]).'<hr>';

//场景三:执行类中的静态方法
class Hello2
{
    public static function add($m,$n)
    {
        echo $m + $n;
    }
}
//Hello2::add(20,30);   数组[类名,方法],[]
call_user_func_array(['Hello2','add'],[40,20]).'<hr>';

2.后期静态绑定案例

class Db1
{
    public static $pdo = null;
    public static function  connect()
    {
        self::$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
    }

    public static function query()
    {
        $stmt = self::$pdo->prepare("SELECT `name`,`salary` FROM `staff` LIMIT 3");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function select()
    {
        self::connect();
        return self::query();
    }
}

class Db2 extends  Db1
{
    public static function query()
    {
        $stmt = self::$pdo->prepare("SELECT `name` AS `姓名`,`email` AS `邮箱` FROM `user` LIMIT 3");
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

}
echo '<pre>';
print_r(Db1::select());


Correction status:qualified

Teacher's comments:
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