Which visibility to declare for classes methods?

Which visibility to declare for classes methods?

by Joseph Rézeau -
Number of replies: 2
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers Picture of Translators

Hi all,

I am currently taking on the (huge) task of making the Questionnaire plugin fully compliant with the Moodle Coding style.

The Code checker throws this error: "No scope modifier specified for function ...". The Code Style says: "Methods inside classes must always declare their visibility by using one of the private, protected, or public modifiers. "

If I declare those functions' visibility using one of those 3 modifiers, it keeps the Code checker happy. However, and this is the reason for my question, I have not the faintest idea which of those 3 modifiers I should use in my functions.

Joseph

 

Average of ratings: -
In reply to Joseph Rézeau

Re: Which visibility to declare for classes methods?

by Michael Aherne -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

Hi Joseph

If the method is called from code outside of the class itself (or any subclasses of it) it needs to be public. Otherwise protected will normally be fine, unless you want to explicitly prevent the method being called by subclasses.

The various rules are detailed in the PHP documentation here

Cheers

Michael

Average of ratings:Useful (1)
In reply to Michael Aherne

Re: Which visibility to declare for classes methods?

by Joseph Rézeau -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers Picture of Translators

Thanks, Michael, just what I needed.

Joseph