开发者

Problem with optional arguments in PHP

I have a function which takes four optional arguments:

public function doSomething($x = null, $y = null, $a = null, $b = null) {  }

However when I try to call this function and specify only $y for instance:

$object->doSomething($y=3)

It seems t开发者_开发技巧o ignore that I am setting $y as 3, and instead sets $x to be 3. Is there any reason why this might happen with PHP? I never used to have this issue before...

Thanks,

Dan


You must pass arguments in the order that you declare in your method signature, whether they're optional or not. That means you must specify $x before $y, no matter what.

If you don't need to pass any other value of $x, you'll have to pass null. You can still skip the remaining optional arguments, of course:

$object->doSomething(NULL, 3)

Additionally, PHP does not support named arguments. Therefore, you cannot explicitly write $y in the calling code because in PHP that actually sets $y within the scope of the calling code, and not the scope of doSomething()'s method body.

EDIT: per dpk's suggestion, as an alternative route you can change the method to accept a hash (associative array) instead, and optionally overwrite some defaults and extract() the values of it into scope:

public function doSomething(array $args = array()) {
    $defaults = array('x' => NULL, 'y' => NULL, 'a' => NULL, 'b' => NULL);
    extract(array_merge($defaults, $args));

    // Use $x et al as normal...
}

In your calling code:

$object->doSomething(array('y' => 3));


Even though $x is optional, the position is not so $y needs to be the second parameter. Try:

$object->doSomething(null,3);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜