Jump to content

Pattern for methods and properties


Manaus
 Share

Recommended Posts

I cannot grasp the pattern behind the object method/properties:

$page->hasChildren() // or $page->hasChildren ?
$page->id(); // or $page->id ?
$children->count() // or $children->count ?

I mean, when to use parentheses, and when not? Is there a principle behind this?

Usually after a couple of attempts I manage to get it working, but I'd like to have the idea come natural, without thinking.

Thank you very much

 

Link to comment
Share on other sites

You don't know what to use when because ProcessWire does some magic here to make both versions work most of the time. For example the method to get children of the current page is $page->children() (https://processwire.com/api/ref/page/children/) but $page->children will work as well.

ProcessWire does that using magic methods (https://www.php.net/manual/en/language.oop5.magic.php) so when you request $page->children it will check if a method "children" exists and will call that method for you even though you are accessing it as a property and not as a method.

So requesting the method directly might be slightly more efficient, but in most cases I guess it will not matter. And imho using the "property syntax" like $this->wire->files->render() is cleaner than always using methods. $this->wire()->files()->render()...

  • Like 3
Link to comment
Share on other sites

4 hours ago, Manaus said:

I mean, when to use parentheses, and when not? Is there a principle behind this?

Usually methods do something and properties hold a value. So $pages->count() would be a method whereas $page->id would access the id property of the page object...

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...