php 构造函数支持不同个数参数的方法

php 构造函数支持不同个数参数方法

原理:在__construct中使用 func_num_args 获取参数个数,再根据参数个数执行不同的调用。参数值使用func_get_arg() 方法获得。


demo:

<?php
class demo{

    private $_args;

    public function __construct(){
        $args_num = func_num_args(); // 获取参数个数

        // 判断参数个数与类型
        if($args_num==2){
            $this->_args = array(
                                'id' => func_get_arg(0),
                                'dname' => func_get_arg(1)
                            );
        }elseif($args_num==1 && is_array(func_get_arg(0))){
            $this->_args = array(
                                'device'=>func_get_arg(0)
                            );
        }else{
            exit('func param not match');
        }    
    }

    public function show(){
        echo '<pre>';
        print_r($this->_args);
        echo '</pre>';
    }

}

// demo1
$id = 1;
$dname = 'fdipzone';
$obj = new demo($id, $dname);
$obj->show();

// demo2
$device = array('iOS','Android');
$obj = new demo($device);
$obj->show();
?>

demo执行后输出:

Array
(
    [id] => 1
    [dname] => fdipzone
)
Array
(
    [device] => Array
        (
            [0] => iOS
            [1] => Android
        )

)


原文地址:https://www.cnblogs.com/fdipzone/p/3715053.html