Reasons to avoid access modifiers in php [closed]

2019-01-18 00:42发布

What are valid reasons NOT to use keywords public, private, protected in php?

The story: I've started a project with a team that actively uses access modifiers in their code (even "public" explicitly) and wants to convince me to do the same. I always find this kind of stuff totally useless in a dynamic language like php, but I realize that my gut feeling is hardly an argument in a technical discussion. Therefore I'm looking for a solid, clear explanation why access modifiers are useless (or even harmful) in php.

I'm aware that some similar topics already exist

however there are several reasons why I'm posting this one

  • I am not asking if I should use "public" or not. I'm already not using it.
  • I am explicitly not interested to hear why access modifiers are good (I know they're bad, I just need an expert to confirm that).
  • If you're about telling me about "best practices" and "principles of OOP", please do not bother.

TIA

4条回答
孤傲高冷的网名
2楼-- · 2019-01-18 01:02

mario nailed it (copied from the comments)

Access modifiers make sense in Java/C++ and compiled code in general, where they are enforceable. In uncompiled scripting languages they can easily be ripped out. Hence they should be considered just decorators, and thus pragmatically could just be implemented as coding convention. (See underscoritis in Python, and pretty much any other scripting language. PHP is pretty alone with its purposeless access decorators.)

You won't have much success convincing your teammates about the advantage of useful APIs over encapsulation by restrictiveness. The use of syntax-enforced access decorators is often cargo cult driven.

查看更多
Animai°情兽
3楼-- · 2019-01-18 01:08

In a dynamic language like PHP, it is assumed that the programmer knows how the code works. That means the programmer knows which methods to call and which should not be called directly.

This is similar to untyped variables: in typed languages each variable is explicitly typed, but in PHP it is assumed that the programmer knows the type of each variable.

查看更多
家丑人穷心不美
4楼-- · 2019-01-18 01:17

valid reasons NOT to use keywords public, private, protected in php?

查看更多
祖国的老花朵
5楼-- · 2019-01-18 01:18

The private modifier is - imho - vastly overused. The problem with it is that it makes it impossible to extend classes. But more importantly, it is a concept that leads one to write code which is class-oriented, rather then object-oriented.

I have no beef with protected for properties. In fact, I think it should be the only scope used. protected methods are usually a hassle though, as it makes testing harder.

查看更多
登录 后发表回答