php 类的 私有 公共,PHP類常量——公共的、私有的還是受保護的?

19

Class constants should have the option of being private/protected because being public exposes internal details of the class that other classes/code can mistakingly use thinking they are ok to use because they are public.

類常量應該可以選擇為private/protected,因為它公開了類的內部細節,其他類/代碼可能會錯誤地認為它們是可以使用的,因為它們是公共的。

It would be nice to know that changing a private constant would ONLY affect the class it's defined in. Unfortunately we don't have that option.

如果知道改變一個私有常量只會影響它所定義的類,那就太好了。不幸的是,我們沒有這個選擇。

Remember back to when you were learning Object Design & Analysis... you give class methods and attributes the most RESTRICTIVE access possible, and later relax them as needed (much harder to go back the other way because other classes/code start using them which would then break other code).

還記得你學習對象設計和分析的時候嗎?您為類方法和屬性提供了最嚴格的訪問權限,然后根據需要放寬它們(更難以回到相反的方式,因為其他類/代碼開始使用它們,這會破壞其他代碼)。

WORKAROUND

解決方案

Best bet is to just create a private or protected variable and upper-case it to show it's a constant. You could always create a class called constant($value_to_be_constant) that implements the correct magic methods / spl interfaces to prevent it from being changed.

最好的方法是創建一個私有的或受保護的變量,用大寫字母表示它是一個常數。您可以創建一個名為常量的類($value_to_be_constant),它實現正確的魔術方法/ spl接口,以防止更改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值