gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:54:46 26 4
gpt4 key购买 nike

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

26 4 0