This is a practice I’ve seen before, but not very often: A variable is assigned to a value at the same time the value itself is evaluated (or is it the expression itself that is evaluated?). Example:
// Outputs "The value is 1"
$value = 1;
if ($var = $value) {
echo "The value is $var";
}
Seems to be the same as:
$value = 1;
$var = $value;
if ($var) {
echo "The value is $var";
}
Another example:
// Outputs "The value is 1"
$value = 1;
echo "The value is ".$var = $value;
I’ve been using this a little bit to shorten up my code, mainly the first example: for evaluating the first variable or expression while assigning it to another within the same expression. Something like this:
if ($status = User::save($data)) {
echo "User saved.";
}
// do something else with $status
This seems so basic, but I can’t actually find any documentation on this, maybe I’m not sure where to look. I’ve only recently figured out how this works after seeing it for years, and I really like using it, but I don’t want to use it haphazardly.
It makes code shorter, maybe not quite as clear to some, but definitely less repetitive. Are there any caveats with this method? Is this perfectly safe or are there any cases where it might fail or cause unexpected behavior? This doesn’t seem to be a very common practice, so I was hoping to find an explanation before I start “going nuts” with it. If it is documented, links to the correct page will be much appreciated.
From https://www.php.net/manual/en/language.expressions.php:
Many people would argue that you shouldn’t use this behaviour very often. For instance, distinguishing between:
and
is tricky! The two common idiomatic ways of writing the above to distinguish them:
The first is called a yoda condition and causes a syntax error if a equals character is left out. The latter won’t behave any differently when run, but some code checkers will output warnings when the expression doesn’t have the extra parentheses.