开发者

PHP creating a new object or use existing one if isset?

开发者 https://www.devze.com 2023-04-09 11:05 出处:网络
Many times i find this redundan开发者_运维知识库t: $found = $repo->findOneByCode($code); $zone = isset($found) ? $found : new Zone();

Many times i find this redundan开发者_运维知识库t:

$found = $repo->findOneByCode($code);
$zone = isset($found) ? $found : new Zone();

Can anyone suggest a better way, similar to (not working):

$zone = $repo->findOneByCode($code) || new Zone();

EDIT: i can't modify Zone and findOneByCode as they are auto-generated classes and function by Doctrine ORM.


If you're using >= PHP 5.3

$zone = $repo->findOneByCode($code) ?: new Zone();

otherwise maybe this is better? (still a bit ugly)...

if ( ! ($zone = $repo->findOneByCode($code))) {
    $zone = new Zone();
}

Assuming on failure, $repo->findOneByCode() returns a falsy value...


What you're describing is a lazy singleton pattern. This is when there is only ever one instance of the class, but it doesn't get initialized until you try to use it.

Example: http://blog.millermedeiros.com/2010/02/php-5-3-lazy-singleton-class/


You can do the following:

$zone = ($z = $repo->findOneByCode($code)) ? $z : new Zone();

Note, however, that this does not work exactly like using isset(). While using isset() will allow other falsey values other than NULL to pass through (such as FALSE), using a ? b : c will resolve to c on all falsey values.


These two methods will also do the job:

$zone = $repo->findOneByCode($code) or $zone = new Zone();

($zone = $repo->findOneByCode($code)) || ($zone = new Zone());

Note that or and && have different precedences and that is why we need the () in the second example. See http://www.php.net/manual/en/language.operators.logical.php. The example there is:

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;

var_dump($e, $f);

And the result:

bool(true)
bool(false)

This is because and and or have lower precedence than = meaning the assignment will be done first. On the other side, && and || have higher precedence than = meaning the logical operation will be done first, and its result assigned to the variable. That is why we cannot write:

$result = mysql_query(...) || die(...);

$result will hold the result of the logical operation (true or false). But when we write:

$result = mysql_query(...) or die(...);

the assignment is done before the logical operation. And if it is not falsely value, the part after the or is cimpletely ignored.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号