Can someone explain this line of code, please? (Logic and assignment operators)

I saw the following lines of code, and I know what they do, but I don’t know how the second line works (and therefore how to apply it to another situation).

$user = User::model()->findByPk(123);
empty($user->profile) and $user->profile = new Profile();

The code tries to find the user from the database, and if there is no profile, a new one is created for use later.

I also saw the code before something like the following:

$variable1 = $variable2 = $variable3;

He did something more complicated than just assigning the three things the same, but I can’t find this type of thing to find out any information about this, let alone find the source code that I came across. I think he initially had an "and." Does anyone know how to look for code that has more than one equal sign that was not just an if statement?

Sorry for the two questions in one (and vague in this) and the terrible headline (I will correct this when I find out what these names are, if it is something like a shadowy statement)).

+1
source share
6 answers

Using logical operators to skip code : Since php evaluates the line with the AND operator, if the first part is false, the second part is not evaluated, since it will not change the result.

So, in this case, if it empty()returns true, then php evaluates the right side. If it empty()returns false, the evaluation is no longer performed and the profile is not executed.

In the php manual, logical operators have some illustrations of this.

: .

$variable1 = $variable2 = $variable3;

$variable2 $variable3, $variable1 $variable2. php manual .

+5
empty($user->profile) and $user->profile = new Profile();

and, ; , , , . , .

php docs.

+2

,

if (empty($user->profile))
    $user->profile = new Profile();

...

+1

. PHP, false, .

:

if (x == 5 and y == 2)

, x == 5, , , , y == 2. x!= 5, y == 2. , , $user- > . , , , $user- > profile = new Profile(); , :

if (empty($user->profile))
    $user->profile = new Profile();

empty($user->profile) ? $user->profile = new Profile();

, = , , $variable1 $variable2, $variable3.

PHP , . :

http://us.php.net/manual/en/language.expressions.php

0
$variable1 = $variable2 = $variable3;

( ) PHP . PHP . $variable3 $variable2. $variable2 = $variable3 $variable1.

0

All Articles