Leo Jiang
Leo Jiang

Reputation: 26085

What is this PHP technique called?

I've seen something like this used in WordPress:

if($aVariable=aFunction()){
  // If aFunction() returned true
}

What is this called and where can I find more information about it?

Upvotes: 0

Views: 123

Answers (3)

deceze
deceze

Reputation: 522042

This works because the value of an assignment expression is the assigned value.

$foo = 'bar' is an assignment expression. This expression assigns the value 'bar' to the variable $foo and the expression as a whole also results in the value 'bar'.

if () expects an expression inside the parentheses that it will evaluate to true or false.

So it boils down like this:

if ($aVariable = aFunction())
if (value of expression, which is whatever aFunction() returned)
if (true/false evaluation of value of expression)

I don't know if there's a specific name for that.

Upvotes: 0

Ira Baxter
Ira Baxter

Reputation: 95334

"Inline assignment" is what I'd call it.

It is equivalent to:

$aVariable=aFunction();
if($aVariable){ 
  // If aFunction() returned true 
} 

And if $aVariable isn't used somewhere else, it is pointless to do this. So someplace else there needs to a useful read of $aVariable.

There isn't a lot else to say about this, except that it saves a few keystrokes, when you need to check the result of aFunction more than once.

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477020

It's called a "conditional". The documentation has the details.

Upvotes: -1

Related Questions