編碼的世界 / 優質文選 / 文明

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


2022年5月18日
-   

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

熱門文章