Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 475
user2318128 Avatar asked Nov 21 '25 04:11

user2318128


1 Answers

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

like image 132
raina77ow Avatar answered Nov 22 '25 16:11

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!