php - 为什么在 PHP 中将 public 放在静态函数之前?

标签 php visibility static-methods

<?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>';
        }
    }
}
?>

问题:

我在上面的 php 文件中看到了这个,static默认为 public , 对?那为什么要放public static function ,而不是 static function ,背后有什么原因吗?

最佳答案

static函数实际上可以定义为protectedprivate (考虑另一个公共(public)静态方法使用的一些实用方法),你是对的,默认情况下它是 public .

实际上,非静态方法是public默认情况下。引用 doc :

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



为什么在此处明确指定该修饰符?好吧,可能它是由支持 Python 最大值的 PHP 团队编写的:explicit is better than implicit .这种方法最明显的优点之一是代码的统一性:对于每种方法,都有一个清晰可见的修饰符。

这就是为什么这样的规则......

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



... 在许多团队和项目的编码约定中并不少见(此特定规则来自 ZF2 coding standards 的引用)。

关于php - 为什么在 PHP 中将 public 放在静态函数之前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16908407/

相关文章:

javascript - 使用 jQuery 在单击按钮上传递值

android - 如何让我的按钮在 TextChanger 中可见?

javascript - 从 anchor html 标记调用 javascript 函数

php - 访问静态变量定义中的静态方法

java - 静态方法和实例方法的区别

java - 静态方法内存分配

javascript - 在 JavaScript 和 vxml 中使用多个转接号码

php - 比较数组和表并删除差异

php - Asterisk :检测来电

php - PHP 类中的可见性重要吗?为什么?