2

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 to 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

2 Answers 2

6

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));
Sign up to request clarification or add additional context in comments.

2 Comments

Right. The way to do this as the OP expects is to pass a single hash as the argument (array('y' => 3)) or some similar data structure (object..)
Thanks for that - for some reason I was under the assumption you could do what I was doing. Must have been another language creeping in!
1

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

$object->doSomething(null,3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.