php私有公共属性,php – OOP – 使用私有属性和公共getter

统一访问原则(UAP)强调模块的服务应通过统一的接口提供,无论其内部实现是存储还是计算。这使得客户端代码无需关心数据获取方式,增强了封装性和API稳定性。举例说明,一个`Now`类初始提供直接的时间戳访问,后来改为计算明天的时间戳。如果一开始就使用getter方法,更改实现时不会影响客户端代码。遵循UAP可以避免不必要的重构,并鼓励使用getter以隐藏内部实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Accessors满足

Uniform Access Principle.

引用维基百科:

The Uniform Access Principle was put forth by Bertrand Meyer. It states “All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation.” This principle applies generally to object-oriented programming languages. In simpler form, it states that there should be no difference between working with an attribute, precomputed property, or method/query.

It effectively means that a client of the person should neither know nor care whether the age is stored or computed. This gives the person object the flexibility to change between the two easily as well as removing what is usually an unnecessary concern from the client. It’s an important part of encapsulation – or at least the data-hiding aspect of encapsulation.

为了说明这一点,想象一下这样的一个类:

class Now

{

public $timestamp;

public function getTomorrow()

{

return strtotime('+1 day', $this->timestamp);

}

// … more code

当您这样做时,您正在强制开发人员使用该类来了解实现细节.要获得现在的时间戳,开发人员必须这样做

echo $now->timestamp;

而要获得明天的计算时间戳,开发人员必须这样做

echo $now->getTomorrow();

但开发人员不需要关心,因此如果您想要遵循UAP,您将提供一个Accessor来获取时间戳.并通过方法汇集所有访问权限.

这样做还具有更稳定的API的额外好处.想象一下,您需要在项目的后期更改实现细节,并将时间戳转换为DateTime对象.你的班级现在看起来像这样:

class Now

{

public $dateTime; //

public function getTomorrow()

{

return strtotime('+1 day', $this->dateTime->getTimestamp());

}

// … more code

现在,任何以前使用过$now-> timestamp的开发人员都必须更改其消费代码以适应该更改.虽然从一开始就使用了Getter,但它根本不是问题,因为Getter会确保它返回时间戳.为了进一步证明这一点,请注意开发人员如何不必更改任何内容以使用getTomorrow().虽然在内部我们更改了细节,但公共API的行为仍然相同.

请注意,UAP只是一个指导原则.现代IDE使您可以轻松地为您生成Accessors和Mutators,因此很容易理解.但这不是绝对的事实.如果您可以合理地证明不遵守它,那么请不要遵循它并使用公共属性.但它应该是一个明智的决定.

但是,总的来说,you want to avoid Getters(和Setters)无论如何都是just tell your objects what to do.这将给出一个更加纤薄的API.如果您的API有很多很多Getters,那么您很可能会将对象内部的代码分散到消费者中.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值