向数组中添加空值

6
我有这个方法:
public function search($searchKey=null, $summary=null, $title=null, $authors=null, $paginationPage=0) { 
    ... 
}

我正在尝试使用以下代码检索所有参数:

$Class = new Search();

// Get parameters
$ReflectionMethod = new \ReflectionMethod($Class, "search");
try {
    foreach($ReflectionMethod->getParameters() AS $Parameter) {
        if(array_key_exists($Parameter->name, $this->params)) {
            $parameters[$Parameter->name] = $this->params[$Parameter->name];
    } elseif($Parameter->isDefaultValueAvailable()) {
        $paramaters[$Parameter->name] = $Parameter->getDefaultValue();
    } else {
            ...
    }
} catch(\Exception $e) {
        ...
}
    // Call function
return call_user_func_array(array($Class, "search"), $parameters);

我的$this->params包含以下内容:

array
  'paginationPage' => int 2
  'id' => int 30
  'searchKey' => string 'test' (length=4)

因为$summary, $title和$authors不存在,它们将获得默认值null。当给参数赋予null值时,它会被跳过,导致$parameters数组看起来像这样:
array
  'searchKey' => string 'test' (length=4)
  'paginationPage' => int 2

当调用一个类的方法时,会返回什么结果:

public function search('test', 2, null, null, 0) { 
        ... 
}

应该是这样的:

public function search('test', null, null, null, 2) { 
        ... 
}

希望您能看到问题。我该如何确保这些空值也被放入我的$parameters数组中。添加无效值是不可能的,因为它是用户输入,所以基本上可以是任何值。
编辑
在上面的示例中,方法search是硬编码的。但其中一个简化的事情是search实际上是一个变量,因此search可以是任何内容。这意味着我不知道方法的参数是什么,也不能在foreach循环之前预定义它们。预定义参数的解决方案实际上正是这段代码应该做的事情。

当你将null值分配给数组时,它会被跳过是什么意思?当我向数组中添加null时,键存在于数组中:http://codepad.org/zIl0wArH - Felix Kling
1
我认为这是问题中的一个笔误。我已将其更改为在将空值分配给参数时 - pts
2个回答

7

在进入 foreach 循环之前,预先初始化 $parameters 如何?

$parameters = array(
    $searchKey => null,
    $summary => null,
    $title => null,
    $authors => null,
    $paginationPage => 0
);

0

哦天啊...只是一个简单的拼写错误:

...
} elseif($Parameter->isDefaultValueAvailable()) {
    $paramaters[$Parameter->name] = $Parameter->getDefaultValue();
} else {
...

真丢人!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接