3
<?php
class newProfileTabs_Listener
{
    public static function template_hook ($hookName, &$contents, array $hookParams, XenForo_Template_Abstract $template)
    {
        if ($hookName == 'member_view_tabs_heading')
        {
            $contents .= '<li><a href="{$requestPaths.requestUri}#ourTab">Our Tab</a></li>';
        }
    }
}
?>

Question:

I saw this above php file, static by default is public, right? so why put public static function, not static function, is there any reason behind?

2
  • Honestly, it's probably a holdover of convention from C++/Java, where (I believe) the "public" keyword would not be optional. Of course, the keyword is optional in PHP5 for backwards compatibility with PHP4, which had no concept of visibility. Commented Jun 4, 2013 at 1:29
  • @FrankFarmer is right. Also this improves the readability of the code and with an good editor it isn't to much to type.
    – TheHippo
    Commented Jun 4, 2013 at 10:15

1 Answer 1

4

While static function can actually be defined as protected and private (consider some utility methods used by another, public static method), you're right, by default it's public.

In fact, non-static methods are public by default too. Quoting the doc:

Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.

Why is that modifier specified here explicitly? Well, probably it was written by the PHP team that supports the Python's maxima: explicit is better than implicit. One of the most obvious advantages of such approach is uniformity of the code: for every method there's a modifier that's clearly seen.

That's why rules like this...

Methods inside classes MUST always declare their visibility by using one of the private, protected, or public visibility modifiers.

... are not incommon in many teams' and projects' coding conventions (this particular rule was a quote from ZF2 coding standards).

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