I have a quick question regarding PHP’s return statement. In C++, we’re able to perform the following:
... function body ...
return (foo = bar, biz());
Where the variable bar is assigned to foo before the result of biz() is returned.
Is this possible (or something similar) in PHP? The above statement in PHP results in a parse error. Now, I’m aware that I can simply perform the assignment before the return statement, but this is just a contrived example, and I’m curious as to the feasibility.
Edit: Providing a little more clarification. Here is what I’m basically attempting to do in PHP:
return ($foo = $bar, biz())
|| ($foo = $bar, baz())
|| ($foo = $bar, qux());
foo is a global reference in which biz modifies. If biz returns false, the next segment in the OR statement is tested. Because biz returned false, I need to “reset” the value of foo before executing baz and so on and so forth.
I’m aware that what I’m trying to do here is impure, but I’m just curious is an equivalent (or at least similar thing) is possible in PHP.
No, unfortunately PHP doesn’t actually have a comma operator except in expr1 of a for loop. Everywhere else a comma is just used to separate arguments to a function or language construct.
You could sort make your own comma operator user function, which just returns the last argument passed into it. Here’s my shot at it:
With this you could use:
The following complete code outputs
Hello:Edit
Your sample code, using the comma function, would look like this:
I honestly can’t recommend using this though. That is why my short answer is “No”.