Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple parameters to a method in PHP

I'm working on a simple class right now to get my head around OOP and I need some help with a function. The function receives various parameters, some of are optional:

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

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.

like image 452
Vinny Avatar asked Jun 08 '26 22:06

Vinny


2 Answers

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);
like image 81
NullUserException Avatar answered Jun 10 '26 11:06

NullUserException


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

like image 43
zserge Avatar answered Jun 10 '26 10:06

zserge