DanielaWaranie
DanielaWaranie

Reputation: 1415

How to imitate list() with own function / method in PHP?

We all know calls like this:

list($a, $b) = explode(':', 'A:B');

But how to make a custom function that can be use the same way?

$obj->mylist($a, $b) = explode(':', 'A:B');
mylist($a, $b) = explode(':', 'A:B');

If i use the above lines of code i always get: "Can't use method return value in write context in [...]" How to define the function / class method to accept that type of assignment? How to the the array returned by explode()? Via func_get_args()?

Sure, there are other ways to assign the result of explode(), but that is not the subject of this question. E.g.

$obj->mylist($a, $b, explode(':', 'A:B'));
mylist($a, $b, explode(':', 'A:B'));

Upvotes: 1

Views: 86

Answers (3)

mickmackusa
mickmackusa

Reputation: 47904

Yes, PHP allows array-type data to be "spread" into individual method parameters via the spread operator.

Code: (Demo)

class Test
{
    public function mylist(string $a, string $b): void
    {
        var_dump($a, $b);
    }
}

$obj = new Test();
$obj->mylist(...explode(':', 'A:B'));

Output:

string(1) "A"
string(1) "B"

If your goal is not to directly pass the values into a method as parameters, then perhaps your requirements aren't very clear and we should be told what mylist() does.

Upvotes: 0

Paul
Paul

Reputation: 141827

You can't do that. list() is a language construct, not a function, and there is no way in PHP to make a function behave like that. It will cause a syntax error.

What meaning would you want from mylist($a, $b) = explode(':', 'A:B'); anyways? If it were list instead of mylist it would just be equivalent to:

$arr = explode(':', 'A:B');
$a = $arr[0];
$b = $arr[1];
unset($arr);

How could you redefine the meaning of that for a function on the left? With your object example you can do something like:

list($obj->a, $obj->b) = explode(':', 'A:B');

What behaviour exactly are you trying to get? Perhaps there is another way.

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318518

It is impossible as you cannot write a method that can be used as an lvalue.

list() is not a function but a language construct, that's why it can be used in the way it's used.

Upvotes: 8

Related Questions