0

Today, I learnt named arguments in PHP but I have a question regarding how to use them dynamically. I mean generating the arguments object. Here is the example

function getVar(
    String $a = null,
    String $b = null,
    String $c = null
){
    ///EXAMPLE FUNCTION
}

Then, if we want to call the function we should do

$this->getVar(a: 'test',b:'test',c: 'test');

So, I have question, how do we call the argument objects from creating object

$object = {
'a'=>'test',
'b'=>'test',
}

//Whenever I want to add 'c' it is possible to add dynamically
if($user=='admin') $object['c'] = 'test'

$this->getVar($object);

I want to achieve how the code above works. I have no idea is it possible or not because there are many condition and I need to generate the variable based on the needs of user input, I cannot make the way to call the function being static or creating many condition.

I am thinking the only way to do it is to separate it into a json object and send to function. Then, we decode and read the variable inside its function.

  • Instead, make your function accept array\object of values. – u_mulder May 29 '23 at 08:30
  • Why would you need to go through JSON?! At the very least, a regular PHP *array* would do. But better than that, PHP *does* support unpacking of associative arrays to named arguments; see the [dupe linked](https://stackoverflow.com/a/64997399/476) above. – deceze May 29 '23 at 08:31
  • @deceze some function could call a curl which content is json, I mean, of course it would be an array. Anyway thank you for your clarification – James Hartford May 29 '23 at 08:34
  • @u_mulder, sure I have do that but I just thinking about making it more clean because its really annoying to use array as arguments, especially when we have lots of parameters there. Except we can send an object "Object $object" instead of "Array $object". I really hope PHP could scope that just like Dart – James Hartford May 29 '23 at 08:38

0 Answers0