6

So here's something I've never been able to figure out about Twig. Does it make a difference if you include the parenthesis for functions or not?

In other words, what is the difference – if any – between calling

craft.entries.first

and

craft.entries.first()

?

6

I think it was Ben Croker who mentioned this nugget from the Twig docs in his Craft course on development:

For convenience's sake foo.bar does the following things on the PHP layer:

  • check if foo is an array and bar a valid element;
  • if not, and if foo is an object, check that bar is a valid property;
  • if not, and if foo is an object, check that bar is a valid method (even if bar is the constructor - use __construct() instead);
  • if not, and if foo is an object, check that getBar is a valid method;
  • if not, and if foo is an object, check that isBar is a valid method;
  • if not, return a null value.

foo['bar'] on the other hand only works with PHP arrays:

  • check if foo is an array and bar a valid element;
  • if not, return a null value.

The more you find out about Twig, the more you don't know!

11

On a more philosophical note; Put yourself in the shoes of first(). It's a method, doing an important job in the Craft eco-system. It prides itself on returning the most important and relevant data in an efficient and unencumbered way. Serving up entry after entry, asset after asset, 24 hours a day, all week, all year. Never complaining, never getting any praise.

And you want to treat it like a simple property? As a dumb, brainless reference to some data that some other method created? How do you think that makes first() feel? How would you feel if someone treated you as property?

I know you're a good person with a big heart, Mats. I'm sure you will do the right thing and treat first() with the respect it deserves, even though it means that you'll have to write a few more characters a day.

  • 1
    If I could give this answer multiple upvotes, I would. FWIW, I do make sure that first() never leaves home without its parentheses. Poor little fella just looks so naked and defenseless without them. – Mats Mikkel Rummelhoff Feb 27 '16 at 13:25
  • 1
    I've never considered having empathy for a method before. – jthomas Feb 24 '17 at 17:15
3

There is absolutely no difference. Twig will recognize a method without parenthesis as simply being a method without parameters.

The only "gotcha" is if you also happen to have a property by the same name in your class. It's probably a bad idea to do so anyway, but if you have a method & property sharing the same name, Twig will parse the parenthesis-less name as the property value instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.