PHP 命名空间是否有完善的命名约定?
到目前为止,我已经看到了许多用于 PHP 命名空间的不同命名约定。有些人使用PascalCase\Just\Like\For\Classes
,有些人使用underscored\lower_case\names
,有些人甚至使用Java约定的包名称:com\域\项目\包
。
问题很简单——这些(或其他)约定中的任何一个都可以称为完善的约定吗?为什么?它们中是否有 Zend 等权威机构或知名 PHP 框架的开发人员推荐的?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由许多不同 PHP 框架和项目的贡献者组成的 PHP 标准工作组针对适当的命名空间使用提出了以下建议:
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
A PHP Standards Working Group made up of contributors to many different PHP frameworks and projects came up with the following proposal for appropriate namespace usage:
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
我不认为你可以说目前已经有任何成熟的东西,但是有一个 RFC 正在讨论 PEAR2 的问题: http://wiki.php.net/pear/rfc/pear2_naming_standards
我的看法是,命名空间是变量的一种形式,因此应该遵循与它们相同的约定。我通常更喜欢使用
lowercase_underscore
作为自由变量(而不是对象成员),因此最适合我口味的是namespace\ClassName
。这也符合其他语言中最流行的约定。另一方面,对于 5.3 之前的伪命名空间也可以提出相同的论点,但这里事实上的标准似乎使用 CamelCase。I don't think you can say there is anything well established at this point, but there is an RFC discussing it for PEAR2: http://wiki.php.net/pear/rfc/pear2_naming_standards
My take is that namespaces are a form of variables, and therefore should follow the same convention as they do. I genereally prefer
lowercase_underscore
for free variables (As opposed to object members), so the most natural for my taste would benamespace\ClassName
. This also matches the most prevalent conventions from other languages. On the other hand, the same argument could be made for pre-5.3 pseudo-namespaces, but here the de-facto standard seems to be using CamelCase.就我个人而言,我喜欢用大驼峰式写出类名,用小驼峰式写写类属性和方法,并用下划线作为前缀。
其他局部变量我也在编写不带下划线前缀的小驼峰形式。对象实例总是写成大驼峰式等等。我真的不认为有最好的方法,你只需要与你的编码标准保持一致。这使您可以更快地阅读代码,并且可以更快地了解哪些代码行发生了什么。
Personally I like writing classnames upper camelcase, class attributes and methods lower camelcase and class attributes prefixed with an underscore.
Other local variables i'm also writing lower camelcase without an underscore prefix. Object instances are always written uppper camelcase etc. etc. I don't really think that there is a best way, you just have to be consistent to your codingstandard. This gives you the advantage of reading faster through your code and it should give a faster insight in what's happening at which codelines.
有些人可能会说
PascalCase except Acronyms/Initialisms
是首选。因此,例如,以下是合适的版本:来源:wiki.php.net
来源:位于 wiki.php.net
PSR-1
来源:在 php-fig.org
Some might say that
PascalCase except Acronyms/Initialisms
is the preferred choice. So, for example, the following are appropriate versions:Source: At wiki.php.net
Source: At wiki.php.net
PSR-1
Source: At php-fig.org