受保护的属性带有下划线 [英] Protected properties prefixed with underscores

查看:275
本文介绍了受保护的属性带有下划线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Like:

public
  $foo        = null,
  $bar        = 10;

protected

  $_stuff     = null,
  $_moreStuff = 5;

很多人似乎这样做。为什么?

A lot of people seem to do this. Why?

这不一致的命名(像一些PHP函数是:))?

Isn't this inconsistent naming (like some PHP functions are :))?

推荐答案

这真的是一件事:个人喜好。

It really comes down to one thing: personal preference.

我个人,也是一个使用命名约定的人。使用下划线(无论是变量还是函数)来前缀任何 protected private ,允许自己和任何其他我经常工作的程序员知道该变量是全局的,并且不能在当前类/上下文之外访问。

I, personally, am also one who uses that naming convention. Prefixing anything that is protected or private with an underscore, be it a variable or a function, lets myself and any other programmer who I regularly work with know that that variable is global and will not be accessible outside of the current class/context.

一个有助于澄清用例的示例是类方法:

An example that helps clarify the use-case would be with class methods:

class Example {
    public function firstFunction() {
        // do stuff
    }

    protected function _secondFunction() {
        // do more stuff
    }
}

当我编写使用类 Example 的代码或者在类本身内部工作时,如果我看到 _secondFunction()我会马上知道它不是一个公共函数,因为开始 _ 可在类外访问;不需要去找到实际的函数声明并查看修饰符。另一方面,我会知道 firstFunction()是公共的,因为它不以一个开头。

When I'm writing code that uses the class Example, or working inside of the class itself, if I see _secondFunction() I will immediately know that it's not a public function because of the starting _ and thereby not accessible outside of the class; no need to go and find the actual function declaration and see the modifier. On the flip side, I will know that firstFunction() is public because it doesn't begin with one.

这篇关于受保护的属性带有下划线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆