0

Is it possible to define a variable in an IF condition, and then use that variable in the same IF condition? My test shows it cannot, however, why it isn't possible escapes me. If so, how? If not, why?

function getX(){return 123;}
function getY($x){return $x*2;}
function getZ($y){return $y*2;}

if(
    true
    && $x=getX()
    && $y=getY($x)
    && $z=getZ($y)
)
    {echo('true '.$x.' '.$y.' '.$z);}
else {echo('false '.$x);}
1
  • Operators precedence? Commented Jan 13, 2014 at 14:48

2 Answers 2

1

Add brackets () to your conditions.

function getX(){return 123;}
function getY($x){return $x*2;}
function getZ($y){return $y*2;}

if(
    true
    && ($x = getX())
    && ($y=getY($x))
    && ($z=getZ($y))
)
    {echo('true '.$x.' '.$y.' '.$z);}
else {echo('false '.$x);}

Working 3v4l: http://3v4l.org/lt3cc

Sign up to request clarification or add additional context in comments.

5 Comments

Good call. Can you explain what is actually happening without the brackets?
Well. Sorry. the comment is off toppic. PHP is not compiled. Is interpreted.
Wasn't questioning the use of "compiler" versus "interpreter". Your answer fixed the problem. Do you know why doing so works?
If you want be fully documented on the php interpreter, you can find here the source code. github.com/php/php-src I do not know how it completly works, sorry.
I think it has to do with the expression evaluation. If you try one assignment alone it should work but once you add others the interpreter will get confused about what you're trying to do. You'll need to dig deeper if you want to understand the internals of thisbehavior i.e looknig into php source code
1

You need to wrap your assignments within the condition into brackets like this:

function getX(){return 123;}
function getY($x){return $x*2;}
function getZ($y){return $y*2;}

if(
    true
    && ($x=getX())
    && ($y=getY($x))
    && ($z=getZ($y))
)
    {echo('true '.$x.' '.$y.' '.$z);}
else {echo('false '.$x);}

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.