Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can php function parameters be passed in different order as defined in declaration

Tags:

php

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)
like image 876
Desmond Liang Avatar asked Jan 08 '11 20:01

Desmond Liang


People also ask

Do parameters have to be in order?

Most programming languages force you to order your function parameters. Getting them wrong might break your code.

Can you pass functions as parameters in PHP?

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.

How many ways you can pass parameter to a function in PHP?

There are two different ways of passing parameters to a function. The first, and more common, is by value. The other is by reference.

How are parameters passed by reference in PHP different from those passed by value?

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.


2 Answers

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'}
like image 157
k0pernikus Avatar answered Nov 14 '22 14:11

k0pernikus


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));
like image 38
Jacob Relkin Avatar answered Nov 14 '22 16:11

Jacob Relkin