naivedeveloper
naivedeveloper

Reputation: 2958

Is it possible to perform an assignment in a PHP return statement?

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.

Upvotes: 3

Views: 2195

Answers (2)

Paul
Paul

Reputation: 141877

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:

function comma(){ return func_get_arg(func_num_args() - 1); }

With this you could use:

return comma($foo = $bar, biz());

The following complete code outputs Hello:

<?php

function foo(){
  $bar = 'Hello';
  return comma($foo = $bar, bar($foo));
}

function bar($foo){
    echo $foo;
}

foo();

function comma(){ return func_get_arg(func_num_args() - 1); }

Edit

Your sample code, using the comma function, would look like this:

return comma($foo = $bar, biz())
    || comma($foo = $bar, baz())
    || comma($foo = $bar, qux());

I honestly can't recommend using this though. That is why my short answer is "No".

Upvotes: 3

effin nukes
effin nukes

Reputation: 76

You could return them in an array

return Array($foo = "bar", biz());

The array will contain:

Array ( [0] => bar [1] => A )

Upvotes: 0

Related Questions