2012-04-11 32 views
0

當調用函數時有沒有簡化參數列表的方法?而不是使用$blank函數簡化參數列表

$subscribe=1; 
    $database->information($blank,$blank,$blank,$blank,$blank,$blank,$subscribe,$blank,$blank,$blank,$blank,$blank); 



    function information ($search,$id,$blank,$category,$recent,$comment,$subscribe,$pages,$pending,$profile,$deleted,$reported) { 
    //code 
    } 

回答

2

你可以通過在指定鍵的數組,並用默認值

數組進行合併所以不是

function foo($arg1 = 3, $arg2 = 5, $arg3 = 7) { } 

你必須

function foo($args) { 
    $defaults = array(
     'arg1' => '', 
     'arg2' => null, 
     'arg3' => 7 
    ); 

    // merge passed in array with defaults 
    $args = array_merge($defaults, $args); 

    // set variables within local scope 
    foreach($args as $key => $arg) { 
     // this is to make sure that only intended arguments are passed 
     if(isset($defaults[$key])) ${$key} = $arg; 
    } 

    // rest of your code 
} 

然後將其稱爲

foo(array('arg3' => 2)); 
2

是的,傳遞一個數組,而不是重構。長長的參數列表通常是一種難聞的氣味。

function information(array $params) {.... 

information(array('search'=>'..... 
+0

我寫了同樣的答覆,一爲陣列的方法。它給你更多的自由和可用性,特別是如果你使用反射或動態調用。 – VAShhh 2012-04-11 09:59:54

+0

我不認爲你可以使用類型提示數組,只有對象。 – 2012-04-11 10:00:47

+0

http://php.net/manual/en/language.oop5.typehinting.php是的,你可以 – VAShhh 2012-04-11 10:03:06

0

你可以把它因此函數西港島線自動像一個空字符串給定值填充變量:

function information ($subscribe, $search="", $id="", $blank="", $category="", $recent="", $comment="", $pages="", $pending="", $profile="", $deleted="", $reported="") { 
    //code 
} 
2

十二參數通常過多,一個功能。很可能通過重構function information來簡化代碼(包括參數列表變短),看起來很可能是一個怪物。

,你可以在此期間使用治標的辦法是

  • 添加默認參數值
  • 使得函數接受其所有參數作爲一個數組

上面兩種情況,將要求您請訪問全部調用網站的功能進行審查和修改。

添加默認參數是恕我直言糟糕的選擇在這裏,因爲通過看實例調用它似乎是你需要做所有參數默認情況下,這反過來又意味着,編譯器不會警告你,如果你調用功能錯誤。

轉換爲數組是更多的工作,但它會強制您以不會偶然錯誤的方式重寫調用。如果你想所有參數是可選的函數簽名會改變到

function information(array $params) 

或可能

function information(array $params = array()) 

。您可以爲參數提供默認與

function information(array $params) { 
    $defaults = array('foo' => 'bar', /* ... */); 
    $params += $defaults; // adds missing values that have defaults to $params; 
          // does not overwrite existing values 

爲了避免重寫功能體,那麼你可以使用export從數組這些值拔出到本地範圍:

export($params); // creates local vars 
    echo $foo; // will print "bar" unless you have given another value 

See all of this in action

0

是的,有幾種方法:

  • 接受關聯數組作爲一個參數,並通過你需要什麼。如果缺少關鍵參數,則拋出異常。
  • 將關鍵參數放在函數定義的頭部,並在結尾放置可選參數。給他們一個默認值,這樣你就不必聲明他們。
  • Recosinder你的功能。對於一個函數來說,12個參數太多了。考慮使用類/對象,或者在不同函數之間劃分工作。
0

幾種方法:

function test($input = "some default value") { 
    return $input; // returns "some default value" 
} 

function test($input) { 
    return $input; 
} 

test(NULL); // returns NULL 

function test() { 
    foreach(func_get_args() as $arg) { 
     echo $arg; 
    } 
} 

test("one", "two", "three"); // echos: onetwothree