简体   繁体   中英

$variable OR $variable = $variable in PHP

This is a standalone expression in a function:

$var OR $var = $var

What does this expression exactly do?

Never saw this before and can't find the answer as I have no idea how is this called.

Code itself is from: Сodeigniter Template on Github

public function build($view, $data = array(), $return = FALSE)
{
    // Set whatever values are given. These will be available to all view files
    is_array($data) OR $data = (array) $data;
    // Merge in what we already have with the specific data
    $this->_data = array_merge($this->_data, $data);

...

Given an expression like yours

is_array($data) OR $data = (array) $data;

we check the precedence table on http://php.net/operators.precedence first. There we see = is above OR . Thus the line is equal to this:

is_array($data) OR ($data = (array) $data);

Next we have to check the table for associativity. or is left associative so it checks is_array($data) . If that returns true the or expression as a whole returns true and nothing else happens.

If is_array($data) returns false we have to evaluate further, so $data = (array) $data is executed.

In the end this is a "smart" way to write

if (!is_array($data)) {
    $data = (array) $data;
}

Actually in this specific case we could also write only

$data = (array) $data;

As the (array) cast is a no-op if $data already is an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM