php中私有静态属性,PHP pdo实例作为私有静态属性

Obviously, anything that needs to interact with the database will extend this class.

从OOP的角度来看,这没有任何意义.当某个类扩展另一个暗示“是一个”关系的类时.如果你走这条路线,你将很难不违反OCP这是SOLID中的一个字母.

I’ve been flipping back and forth on how to make sure that there is only ever one connection, or PDO object, in a script because some pages will need more than one class that extends Connector.

简单!只需创建一个实例.

Many people seem to recommend a Singleton pattern for this purpose, but the way I currently do it seems to accomplish the same thing.

很多人都不喜欢OOP原则.使用单身人士只是引入了一个“花哨的”global instance / state.

Does this code actually make sense and or am I misunderstanding static properties somehow?

说实话,这更多是对OOP的误解.

Is it bad design/practice and or does Singleton have more advantages?

往上看.

你应该做什么(在OOP中)是inject the database connection进入需要它的类.这使您的代码松散耦合,从而使您的代码更易于维护,可测试,可调试和灵活.

另外,我真的不明白为什么你需要为pdo连接创建一个数据库类,因为PDO API本身已经是OOP.因此,除非你有一个真正的理由为PDO编写一个适配器(可能是这种情况,因为有一些),我会放弃它.

我的€0.02

为了回应您的编辑:

The Connector class wasn’t meant to exist just to hold the PDO object. It’s destructor closes the connection(makes it null).

通常根本不需要关闭连接.处理请求后,连接将自动关闭(除非我们讨论的是持久连接).

and it contains functions such isValueTaken, which checks if a value is already in the database. It has the following abstract functions

这听起来像是另一堂课的工作.

For example I have a User class that extends Connector. It’s defines setData() to register a user in the database. I don’t know if this makes a difference to the response.

不,我的观点仍然存在.用户无需从数据库继承.这听起来不奇怪.从数据库继承的用户(我不想见到那个人).如果需要,您应该将数据库连接注入用户.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值