php 構造函數支持不一樣個數參數的方法

php 構造函數支持不一樣個數參數方法php

原理:在__construct中使用 func_num_args 獲取參數個數,再根據參數個數執行不一樣的調用。參數值使用func_get_arg() 方法得到。函數


demo:this

<?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
        )

)
相關文章
相關標籤/搜索