PHP 不支援方法重載,但可在 __construct 中利用 func_num_args() 獲取參數數量,func_get_arg() 取得參數值,實現「偽重載」。
<?php
class Demo {
private $_args;
public function __construct() {
$args_num = func_num_args();
if ($args_num === 2) {
$this->_args = [
'id' => func_get_arg(0),
'dname' => func_get_arg(1)
];
} elseif ($args_num === 1 && is_array(func_get_arg(0))) {
$this->_args = ['device' => func_get_arg(0)];
} else {
exit('func param not match');
}
}
public function show() {
echo '<pre>';
print_r($this->_args);
echo '</pre>';
}
}
// 用法 1:兩個標量參數
$obj = new Demo(1, 'fdipzone');
$obj->show();
// 輸出: Array ( [id] => 1 [dname] => fdipzone )
// 用法 2:單一陣列參數
$obj = new Demo(['iOS', 'Android']);
$obj->show();
// 輸出: Array ( [device] => Array ( [0] => iOS [1] => Android ) )
?>
func_get_args() 獲取所有參數陣列,配合 ...$args 可變參數語法更優雅