2012-04-11 63 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