A
A
Alexey Nikolaev2014-06-26 00:15:42
PHP
Alexey Nikolaev, 2014-06-26 00:15:42

Are there any side effects in PHP (theoretically) when initializing a variable in an if condition?

Faced a problem.
I am making a plugin on Livestreet (CMS), and I have the following type of code.

if($sFileWebFoto=somefunc() &&
$sFileWebAvatar=somefunc()) {
   //...
}

But it doesn't work. The first condition always returns true in $sFileWebFoto. If you declare variables outside the if conditions, everything will be ok (there should be a string). The second condition returns a string.
The problem is not in the functions mentioned above (100% working kernel functions). I have never noticed this behavior before. And actually a question: what subtlety I missed?
Thanks in advance for your replies!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2014-07-11
@Heian

You asked if PHP has any side effects. Available.
If the first condition is false, then the second condition will not even run at all:

function first()  { echo "first "; return false; }
function second() { echo "second "; return true; }
if (first() && second()) echo "OK"; else echo "Bad";

will print "first Bad", but the word "second" will not be displayed, which means that the second function did not start.
Also, the second condition will not run when using OR if the first condition returned true.
Indeed, why check the second condition if the final result of the expression is already known on the first condition?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question