views:

128

answers:

2

Hello guys,

I'm working on a simple class right now to get my head around OOP and i need some help with a function that i'm creating. The function receives various parameters, being some of those optional. For example:

public function Test($req, $alsoreq, $notreq = null, $notreq2 = null, $notreq3 = null) { 
       // blah blah
}

My question is... how do i call the function, passing the two first parameters and the last one?

For example: Test('req', 'alsoreq', 'notreq3');

Ignoring the notreq2 and notreq?

I tried Test('req', 'alsoreq', '', '', 'notreq3'); but this seems ugly and hackish...

+8  A: 

You can't. Think about it, if you could do that, how would PHP be able to tell if the third argument is supposed to be the $notreq, $notreq2 or $notreq3? A less hackish way would be:

Test($req, $alsoreq, NULL, NULL, $notreq3);

As you are making it clear that the first two optional args are NULL.

Choose the orders of arguments wisely, so the ones that get used more often come first.
Alternatively, you can use an array:

public function Test($req, $alsoreq, array $notreq) { ... }

// no optional args
Test($req, $alsoreq);

$optional = array('arg1' => 'something', 'arg2' => 'something else');
Test($req, $alsoreq, $optional);

$optional = array('arg3' => 'hello');
Test($req, $alsoreq, $optional);
NullUserException
Was going to submit my answer, but I refreshed the page just to check if you edited yours. Alas, you have ;) +1
BoltClock
If you're going to do this, you might as well have Test take only one parameter — an array.
Paul Schreiber
I see... thanks for the tip. Unfortunately, i guess i'll stick to what i was doing, since it's much simpler to treat inside the class.
Vinny
Do you guys know if this is somehow wrong accordingly to the Zend PHP Best Practices?
Vinny
@Vinny, what's considered wrong practice is somewhat of a moot point with PHP, seeing as the language itself isn't very consistent. I used to struggle with such questions, but after working with other languages, I've let go of my guilt and just accepted that, I'm the one working around PHP's limitations. In Python for example you can do this with ease. But PHP doesn't embrace a specific way, some people code as in Java, others as in Perl and others yet as in Python. I suspect the pythonists would be more incline to adopt the implementation showcased in this answer.
mike
+1  A: 

There seem to be no way. As written in php manual:

Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.

You are trying to put non-default value (notreq3) on the right of default (notreq2, notreq1). Ugly and hackish way is likely to be more correct.

Regards, Serge

zserge
Thanks man. Do you know if this is against the PHP best practices?
Vinny