user2318128
user2318128

Reputation: 109

Why put public before static function in PHP?

<?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?

Upvotes: 3

Views: 678

Answers (1)

raina77ow
raina77ow

Reputation: 106483

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

Upvotes: 4

Related Questions