dongxian6653 2014-04-10 15:41
浏览 109
已采纳

PSR-2第4.2节解释

I was recently told by a colleague of mine that PSR-2 coding standard says that you are not allowed to use the "_" character to indicate whether or not the variable is private or protected.

He cited section "4.2 Properties" of http://www.php-fig.org/psr/psr-2/

Visibility MUST be declared on all properties.

The var keyword MUST NOT be used to declare a property.

There MUST NOT be more than one property declared per statement.

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

I was outraged when I heard this because I am a big fan of the _ prefix on private and protected vars and I couldn't believe the community would accept such a standard.

My interpretation of this based on the "SHOULD NOT" keyword was that scope keywords MUST be used when declaring properties on a class and that it is recommended that you not use the _ character, but it is still allowed and you are still PSR-2 complaint if you choose to use this.

While I disagree with this and recommend that everyone prefix their private and protected vars with a underscore, I suspect the reasoning behind this is to prevent people from leaving out the scope keyword ( Public, Protected, Private ) and relying only the naming convention. This makes since, because as we all know with out the scope variable PHP makes everything Public.

http://www.ietf.org/rfc/rfc2119.txt

To summarize the question: Is the "_" prefix on private and protected variables on a class PSR-2 compliant?

Edit: Also, I'm not looking for a personal preference debate here, I just want to know if the use of the _ prefix is technically PSR-2 compliant.

  • 写回答

2条回答 默认 最新

  • doushi1964 2014-04-10 16:14
    关注

    I don't think that "I like it better" qualifies as particular circumstance where valid reasons exist, since the reason would then apply to your person, not the code base or the project.

    I can think of some other examples that justify the SHOULD NOT:

    • Project depends on some third-party tool, framework, whatever... that relies on names to identify visibility.

    • Class method names need to mimic those from other project that use such convention (e.g., because it's a port from another language).

    • Project was started before PHP/5. Renaming would break backwards compatibility.

    Thus it isn't strictly forbidden, but it's clearly discouraged; probably, because it provides redundant information that can get on the way on further refactoring and can even be wrong:

    // r12345 Expose HTML escaping
    public function _escapeHtml(){
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题