In many programming languages, especially the less strictly typed ones, a common coding pattern starts to emerge.
$thing = $this->getSomeThing();
if($thing)
{
//do something with the thing
}
Without a compiler to catch methods returning what they shouldn’t, a developer is forced to sanity check return values from methods before doing anything. This happens in the Magento core code, but you’ll often see it written like this
if($thing = $this->getSomeThing())
{
//do something with the thing
}
Whaaaaaaat? Most programmers know about the “I used an assignment operator (=
) when I meant to use a comparison operator (==
) bug, but some aren’t familiar with deliberately doing this.
Try running the following PHP code
var_dump( ($test = "hi there") );
var_dump( ($test = false) );
Here we’re dumping the results of an assignment.
Your output will be something like
string(8) "hi there"
bool(false)
When you perform an assignment in PHP, it’s actually an expression, and has a return value. Its return value is whatever ends up on the left side of the assignment operator. In other words, whatever you’re putting into the variable will be returned.
So, by deliberately doing this
if($thing = $this->getSomeThing())
{
//do something with the thing
}
a programmer saves a line of code.
If you’re never encountered this pattern before, it can add to mental overhead of understanding a code base (Magento included). You’ll scan code, and often skip over an important method call that does something because you’ve mentally mapped a conditional statement to "oh, that’s just a check” in your head.
Keep an eye out for it!