2010-12-02 31 views
5

我有這個方法:新增null值的數組

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。當分配一個空值參數,將跳過這會導致$參數數組,看起來像這樣:

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循環之前預先定義它們。預先定義參數的解決方案實際上正是這些代碼應該做的。

+0

你是什麼意思*當給數組賦值時,它將被忽略*?當我向數組中添加`null`時,鍵值出現在數組中:http://codepad.org/zIl0wArH – 2010-12-02 08:42:17

回答

0

哦,我...這只是一個簡單的拼寫錯誤:

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

可恥的是我!

6

如何預先初始化$parameters進入foreach循環之前:

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