PHP 创建一个新对象或使用现有对象(如果 isset)?
很多时候我发现这是多余的:
$found = $repo->findOneByCode($code);
$zone = isset($found) ? $found : new Zone();
任何人都可以建议一种更好的方法,类似于(不起作用):
$zone = $repo->findOneByCode($code) || new Zone();
编辑:我无法修改Zone
和findOneByCode 因为它们是由 Doctrine ORM 自动生成的类和函数。
Many times i find this redundant:
$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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是 >= PHP 5.3
否则也许这更好? (还是有点难看)...
假设失败,
$repo->findOneByCode()
返回一个虚假值...If you're using >= PHP 5.3
otherwise maybe this is better? (still a bit ugly)...
Assuming on failure,
$repo->findOneByCode()
returns a falsy value...您所描述的是一种惰性单例模式。这是指该类只有一个实例,但在您尝试使用它之前它不会被初始化。
示例: http://blog.millermedeiros.com/ 2010/02/php-5-3-lazy-singleton-class/
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/
您可以执行以下操作:
但是请注意,这与使用
isset()
的工作原理不同。使用isset()
将允许除NULL
之外的其他 false 值通过(例如FALSE
),使用a ? b : c
将解析为c
所有 false 值。You can do the following:
Note, however, that this does not work exactly like using
isset()
. While usingisset()
will allow other falsey values other thanNULL
to pass through (such asFALSE
), usinga ? b : c
will resolve toc
on all falsey values.这两个方法也可以完成这项工作:
请注意,
or
和&&
具有不同的优先级,这就是我们在第二个示例中需要 () 的原因。请参阅 http://www.php.net/manual/en/language。运算符.逻辑.php。示例如下:结果:
这是因为
and
和or
的优先级低于=
,这意味着赋值将首先完成。另一方面,&&
和||
的优先级高于=
,这意味着逻辑运算将首先完成,其结果分配给变量。这就是为什么我们不能写:$result
将保存逻辑运算的结果(true 或 false)。但是当我们写:赋值是在逻辑运算之前完成的。如果它不是错误值,则完全忽略
or
之后的部分。These two methods will also do the job:
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:And the result:
This is because
and
andor
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
will hold the result of the logical operation (true or false). But when we write:the assignment is done before the logical operation. And if it is not falsely value, the part after the
or
is cimpletely ignored.