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 [...]开发者_JS百科" 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'));
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.
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.
精彩评论