欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-05-13 20:30:39
...
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
        )

)

以上就是php中构造函数支持不同个数参数的方法分享的详细内容,更多请关注其它相关文章!

相关标签: php 个数 不同