首頁  >  文章  >  後端開發  >  關於php 建構子支援不同個數參數的方法介紹

關於php 建構子支援不同個數參數的方法介紹

jacklove
jacklove原創
2018-06-09 14:07:362533瀏覽

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(
                                &#39;id&#39; => func_get_arg(0),
                                &#39;dname&#39; => func_get_arg(1)
                            );
        }elseif($args_num==1 && is_array(func_get_arg(0))){
            $this->_args = array(
                                &#39;device&#39;=>func_get_arg(0)
                            );
        }else{
            exit(&#39;func param not match&#39;);
        }    
    }
    public function show(){
        echo &#39;<pre class="brush:php;toolbar:false">&#39;;
        print_r($this->_args);
        echo &#39;
'; } } // 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中文網。

相關推薦:

如何使用PDO查詢mysql避免SQL注入的方法

關於php 雙向佇列類別的講解

php heredoc 與nowdoc之間的差異與特徵

以上是關於php 建構子支援不同個數參數的方法介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn