为什么我们必须将克隆分配给新变量?
我目前正在学习使用 Propel ORM,并且我想为两个略有不同的查询重用一个条件:
$criteria = ArticleQuery::create()
->filterByIsPublished(true)
->orderByPublishFrom(Criteria::DESC)
->joinWith('Article.Author')
->keepQuery();
$this->news = $criteria
->filterByType('news')
->find();
$this->articles = $critera
->filterByType('article')
->find();
但是,这不会按预期工作,因为现在文章的查询将尝试查找类型均为 ' 的条目新闻”和“文章”,这当然是不可能的。
所以我们需要获得这个对象的克隆,对我来说直观的是简单地在括号内添加克隆关键字:
$this->news = (clone $criteria)
->filterByType('news')
->find();
解析错误:语法错误,意外的T_OBJECT_OPERATOR
相反,我们必须将其分配给变量,然后我们才能使用它:
$clonedCritera = clone $criteria;
$this->news = $clonedCriteria
->filterByType('news')
->find();
您使用 new
运算符具有相同的行为。我看到推进开发人员已经通过替换来规避此限制:new ArticleQuery()->doOperations()
与 ArticleQuery::create()->doOperations()
。
为什么PHP语言设计者选择这样做呢?如果可以直接使用这些表达式的结果,将使代码更加流畅,并且在某些情况下更易于阅读。
I am currently learning to use the Propel ORM, and I want to reuse a critera for two slightly different queries:
$criteria = ArticleQuery::create()
->filterByIsPublished(true)
->orderByPublishFrom(Criteria::DESC)
->joinWith('Article.Author')
->keepQuery();
$this->news = $criteria
->filterByType('news')
->find();
$this->articles = $critera
->filterByType('article')
->find();
However, this won't work as expected, because now the query for articles will try to find entries where the type is both 'news' and 'article', which of course is impossible.
So we need to get a clone of this object, and what seemed intuitive to me was to simply add the clone keyword inside paranthesis:
$this->news = (clone $criteria)
->filterByType('news')
->find();
Parse error: syntax error, unexpected T_OBJECT_OPERATOR
Instead we have to assign it to a variable before we can use it:
$clonedCritera = clone $criteria;
$this->news = $clonedCriteria
->filterByType('news')
->find();
You have the same behaviour with the new
operator. I see the propel developers have circumvented this limitation by replacing:new ArticleQuery()->doOperations()
with ArticleQuery::create()->doOperations()
.
Why did the PHP language designers choose to do it this way? If you could use the result of these expressions directly, it would make the code more fluent and, in some cases, easier to read.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,答案是开发人员还没有开始支持对通过克隆返回的对象进行直接取消引用。
在 PHP 4 中,您无法“取消引用”方法返回的任何对象。您必须首先将其分配给虚拟变量。
在 PHP 的下一个版本中,数组取消引用 将得到支持。
因此,很明显,开发团队在他们的时间表中逐步添加了此类功能。
我能告诉你的最好的办法就是向开发团队请求此功能。
Unfortunately, the answer is that the developers haven't gotten around to supporting direct dereferencing on objects returned via clone yet.
In PHP 4, you couldn't "dereference" any objects returned by method. You had to assign it to a dummy variable first.
In the next version of PHP, array dereferencing is to be supported.
So, it's clear that the dev team incrementally adds such features on their timetable.
The best I can tell you is to request this functionality from the dev team.