我正在寻找一种方法来获取正在设置的参数的值,无论是传递还是预设。我尝试使用func_get_params()
.虽然这会返回正在传入的值,但它不会显示值是否是预设的。
public function __construct($host = 'null', $user = null, $password = null, $database = null){
var_dump(func_get_args());
die();
$this->mysqli = new mysqli($host, $user, $password, $database);
if ($this->mysqli->connect_errno) {
echo("Connection failed: ". $mysqli->connect_error);
exit();
}
}
当没有传入任何值时,获取空数组输出,而不是 null。如果我将nulls
变成字符串,也会发生这种情况。
是否有其他func_get_args
也返回预设值的替代方案?
相当冗长,您会看到为什么命名参数或使用起来更有趣:
<?php
class Foo {
function __construct($host = 'null', $user = null, $password = null, $database = null){
//getParameters
$ref = new ReflectionMethod(__CLASS__,__FUNCTION__);
$args = array();
foreach($ref->getParameters() as $param){
$args[] = $param->getDefaultValue();
}
foreach(func_get_args() as $key => $arg){
$args[$key] = $arg;
}
var_dump($args);
}
}
new Foo();
/*
array(4) {
[0]=>
string(4) "null"
[1]=>
NULL
[2]=>
NULL
[3]=>
NULL
}
*/
new Foo('foo','bar');
/*
array(4) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
NULL
[3]=>
NULL
}
*/