PHP 类方法中的前导下划线有什么关系?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/663350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:24:48  来源:igfitidea点击:

What's the deal with a leading underscore in PHP class methods?

phpcoding-style

提问by nocash

While looking over various PHP libraries I've noticed that a lot of people choose to prefix some class methods with a single underscore, such as

在查看各种 PHP 库时,我注意到很多人选择用单个下划线作为某些类方法的前缀,例如

public function _foo()

...instead of...

...代替...

public function foo()

I realize that ultimately this comes down to personal preference, but I was wondering if anyone had some insight into where this habit comes from.

我意识到这最终归结为个人喜好,但我想知道是否有人对这种习惯的来源有所了解。

My thought is that it's probably being carried over from PHP 4, before class methods could be marked as protected or private, as a way of implying "do not call this method from outside the class". However, it also occurred to me that maybe it originates somewhere (a language) I'm not familiar with or that there may be good reasoning behind it that I would benefit from knowing.

我的想法是,在类方法可以标记为受保护或私有之前,它可能是从 PHP 4 继承而来的,作为暗示“不要从类外部调用此方法”的一种方式。然而,我也想到它可能起源于我不熟悉的某个地方(一种语言),或者它背后可能有很好的推理,我将从中受益。

Any thoughts, insights and/or opinions would be appreciated.

任何想法、见解和/或意见将不胜感激。

采纳答案by Jeremy DeGroot

It's from the bad old days of Object Oriented PHP (PHP 4). That implementation of OO was pretty bad, and didn't include things like private methods. To compensate, PHP developers prefaced methods that were intended to be private with an underscore. In some older classes you'll see /**private*/ __foo() {to give it some extra weight.

它来自于面向对象的 PHP (PHP 4) 糟糕的过去。OO 的实现非常糟糕,并且不包括私有方法之类的东西。作为补偿,PHP 开发人员在本意为私有的方法前加了下划线。在一些较旧的课程中,您会看到/**private*/ __foo() {给它一些额外的重量。

I've never heard of developers prefacing all their methods with underscores, so I can't begin to explain what causes that.

我从来没有听说过开发人员在他们的所有方法之前都用下划线表示,所以我无法解释是什么原因造成的。

回答by joedevon

I believe the most authoritative source for these kinds of conventions for PHP right now would be the PSR-2: Coding Style Guidebecause the Zend Framework is part of PSR:

我相信现在这些 PHP 约定的最权威来源是PSR-2:编码风格指南,因为 Zend 框架是PSR 的一部分:

Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility.

属性名称不应以单个下划线为前缀来表示受保护或私有可见性。

回答by Sliq

Now, in 2013, this is "officially" bad styleby the PSR-2 coding guideline:

现在,在 2013 年,这是PSR-2 编码指南的“官方”错误风格

Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility`

属性名称不应以单个下划线为前缀来表示受保护或私有可见性`

Source: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md

来源:https: //github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md

回答by umpirsky

I was strongly against prefixing private/protected methods with underscore since you can use private/protected keyword for that and IDE will mark it for you.

我强烈反对在私有/受保护的方法前面加上下划线,因为您可以为此使用私有/受保护的关键字,IDE 会为您标记它。

And I still am, but, I found one reason why it can be a good practice. Imagine that you have public method addFoo()and inside that method you have some part of task which is common with other methods addFooWhenBar(), addFooWhenBaz()... Now, best name for that common method would be addFoo(), but it is already taken, so you must come up with some ugly name like addFooInternal()or addFooCommon()or ... but _addFoo()private method looks like best one.

我仍然是,但是,我找到了一个原因,说明它可以成为一种很好的做法。想象一下,您有公共方法,addFoo()并且在该方法中,您有一些与其他方法通用的任务部分addFooWhenBar()addFooWhenBaz()......现在,该通用方法的最佳名称是addFoo(),但它已经被采用,所以你必须想出一些丑陋的名字像addFooInternal()oraddFooCommon()或 ... 但_addFoo()私有方法看起来是最好的。

回答by jonstjohn

Leading underscores are generally used for private properties and methods. Not a technique that I usually employ, but does remain popular among some programmers.

前导下划线通常用于私有属性和方法。不是我通常采用的技术,但在一些程序员中仍然很受欢迎。

回答by GloryFish

I use a leading underscore in the PHP 5 class I write for private methods. It's a small visual cue to the developer that a particular class member is private. This type of hinting isn't as useful when using an IDE that distinguishes public and private members for you. I picked it up from my C# days. Old habits...

我在为私有方法编写的 PHP 5 类中使用前导下划线。对于开发人员来说,特定类成员是私有的,这是一个小的视觉提示。当使用为您区分公共成员和私有成员的 IDE 时,这种类型的提示不是很有用。我从我的 C# 时代拿起它。旧习惯...

回答by Quintin Robinson

I believe your original assumption was correct, I have found it to be common practice for some languages to prefix an underscore to methods/members etc that are meant to be kept private to the "object". Just a visual way to say although you can, you shouldn't be calling this!

我相信您最初的假设是正确的,我发现某些语言在方法/成员等前面加上下划线是一种常见做法,这些方法/成员等旨在对“对象”保持私有。只是一种直观的方式,虽然可以,但您不应该这样称呼!

回答by m.ardito

I was looking for the same answer, I did some research, and I've just discovered that php frameworks suggest different styles:

我一直在寻找相同的答案,我做了一些研究,我刚刚发现 php 框架建议不同的风格:

Code Igniter

代码点火器

The official manual has a coding style section that encourages this practice:

官方手册有一个鼓励这种做法编码风格部分

Private Methods and Variables

Methods and variables that are only accessed internally, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.

私有方法和变量

仅在内部访问的方法和变量,例如您的公共方法用于代码抽象的实用程序和辅助函数,应以下划线为前缀。

public function convert_text()

private function _convert_text()

Other frameworks do the same, like

其他框架也一样,比如

Cakephp:

蛋糕php:

does the same:

做同样的事情

Member Visibility

Use PHP5's private and protected keywords for methods and variables. Additionally, non-public method or variable names start with a single underscore (_). Example:

会员可见度

对方法和变量使用 PHP5 的 private 和 protected 关键字。此外,非公共方法或变量名称以单个下划线 (_) 开头。例子:

class A
{
    protected $_iAmAProtectedVariable;

    protected function _iAmAProtectedMethod()
    {
       /* ... */
    }

    private $_iAmAPrivateVariable;

    private function _iAmAPrivateMethod()
    {
        /* ... */
    }
}

And also

并且

PEAR

does the same:

做同样的事情

Private class members are preceded by a single underscore. For example:

私有类成员前面有一个下划线。例如:

$_status    _sort()     _initTree()

While

尽管

Drupal

德鲁巴

code style specifically warns against this:

代码风格特别警告

  1. Protected or private properties and methods should not use an underscore prefix.
  1. 受保护或私有的属性和方法不应使用下划线前缀。

Symphony

交响乐

on the other hand, declares:

另一方面,声明

Symfony follows the standards defined in the PSR-0, PSR-1, PSR-2 and PSR-4 documents.

Symfony 遵循 PSR-0、PSR-1、PSR-2 和 PSR-4 文档中定义的标准。

回答by Matthew

I know it from python, where prefixing your variables with an underscore causes the compiler to translate some random sequence of letters and numbers in front of the actual variable name. This means that any attempt to access the variable from outside the class would result in a "variable undefined" error.

我从 python 中知道它,在你的变量前面加上下划线会导致编译器在实际变量名之前翻译一些随机的字母和数字序列。这意味着任何从类外部访问变量的尝试都会导致“变量未定义”错误。

I don't know if this is still the convention to use in python, though

我不知道这是否仍然是在 python 中使用的约定,虽然

回答by maho

In Drupal (a php CMS) underscores can be used to prevent hooks from being called (https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7).

在 Drupal(一个 php CMS)中,下划线可用于防止调用钩子(https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7)。

If I have a module called "my_module" and want to name a function my_module_insert it would "hook" on the function hook_insert. To prevent that I can rename my function to _my_module_insert.

如果我有一个名为“my_module”的模块,并且想将一个函数命名为 my_module_insert,它将“钩住”函数 hook_insert。为了防止这种情况,我可以将我的函数重命名为 _my_module_insert。

ps The way hooks works in Drupal it's possible to implement a hook by mistake, which is very bad.

ps 钩子在 Drupal 中的工作方式可能会错误地实现钩子,这是非常糟糕的。