这两种方法也将做的工作:
$zone = $repo->findOneByCode($code) or $zone = new Zone();
($zone = $repo->findOneByCode($code)) || ($zone = new Zone());
注意or
和&&
有不同的优先级,这就是为什么我们的()在第二个例子中所需要的。见http://www.php.net/manual/en/language.operators.logical.php。这个例子有:
// 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);
而结果:
bool(true)
bool(false)
这是因为and
和or
具有优先级低于=
意味着分配将被首先完成。另一方面,&&
和||
具有比=
更高的优先级,这意味着逻辑操作将首先完成,并将其结果分配给变量。这就是为什么我们不能写:
$result = mysql_query(...) || die(...);
$result
将持有的逻辑运算(true或false)的结果。但是当我们写:
$result = mysql_query(...) or die(...);
该分配是在逻辑操作之前完成的。如果它不是虚假价值,or
之后的部分完全被忽略。
http://en.wikipedia.org/wiki/Singleton_pattern –
将'findOneByCode()'方法扩展为返回所需空对象而不是'null'的方法。 – mario