PHP creates a new object or uses an existing one if isset?

Many times I find this redundant:

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

Can anyone suggest a better way similar to (doesn't work):

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

EDIT : I cannot change Zone and findOneByCode since they are automatically generated classes and functions using Doctrine ORM.

+4
source share
4 answers

If you use> = PHP 5.3

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

otherwise , maybe it's better? (still a little ugly) ...

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

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

+4
source

What you are describing is a lazy singleton pattern. This is when there is only one instance of the class, but it is not initialized until you try to use it.

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

0
source

You can do the following:

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

Note that this does not work exactly the same as using isset() . Although using isset() will allow non- NULL falsities to pass (e.g. FALSE ), using a ? b : c a ? b : c will be allowed for c for all false values .

0
source

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 priorities, and therefore we need () in the second example. See http://www.php.net/manual/en/language.operators.logical.php . Example:

 // 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 a lower priority than = , which means that the assignment will be done first. On the other hand, && and || have a higher priority than = , which means that the logical operation will be performed first, and its result will be assigned to the variable. This is why we cannot write:

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

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

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

the assignment is performed before the logical operation. And if this is not false, the part after or completely ignored.

0
source

All Articles