Suppose I have a function/method F() that takes 3 parameters $A, $B and $C defined as this.
function F($A,$B,$C){
...
}
Suppose I don't want to follow the order to pass the parameters, instead can I make a call like this?
F($C=3,$A=1,$B=1);
instead of
F(1,2,3)
Most programming languages force you to order your function parameters. Getting them wrong might break your code.
PHP Parameterized functions are the functions with parameters. You can pass any number of parameters inside a function. These passed parameters act as variables inside your function. They are specified inside the parentheses, after the function name.
There are two different ways of passing parameters to a function. The first, and more common, is by value. The other is by reference.
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
Starting with php@8, php will suppport named arguments.
This will allow passing arguments in a different order as long as you provide their name when calling.
E.g. this may look like:
class SomeDto
{
public function __construct(
public int $foo = 'foo',
public string $bar = 'bar',
public string $baz = 'baz',
) {}
}
$example = new SomeDto($bar = 'fnord!');
// will result in an object { foo: 'foo', bar: 'fnord!', baz: 'baz'}
Absolutely not.
One way you'd be able to pass in unordered arguments is to take in an associative array:
function F($params) {
if(!is_array($params)) return false;
//do something with $params['A'], etc...
}
You could then invoke it like this:
F(array('C' => 3, 'A' => 1, 'B' => 1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With