5

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 newoperator. 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.

CheeseSucker
  • 1,270
  • 1
  • 9
  • 13
  • Hrm. I'm wondering which of my responses would be least inappropriate... – Ignacio Vazquez-Abrams Oct 02 '11 at 21:10
  • why? is indeed a really good question. "because php is not java" was the answer i received , when i asked in some forum about a similar parser issue with "new". in my opinion the php parser has many such flaws -- we can only hope, that they will be fixed someday in future ... – aurora Oct 02 '11 at 21:17
  • @harald I came across this RFC page while researching this, so it appears method instance call is at least under discussion among the PHP developers. https://wiki.php.net/rfc/instance-method-call – CheeseSucker Oct 02 '11 at 22:55

1 Answers1

4

Why must we assign a clone to a new variable?

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.

webbiedave
  • 48,414
  • 8
  • 88
  • 101