面向对象的PHP最佳实践 [英] Object Oriented PHP Best Practices
问题描述
说我有一个代表人的类,该类中的变量将是$ name.
Say I have a class which represents a person, a variable within that class would be $name.
以前,在我的脚本中,我将创建对象的实例,然后仅使用以下命令设置名称:
Previously, In my scripts I would create an instance of the object then set the name by just using:
$object->name = "x";
但是,有人告诉我这不是最佳实践吗?我应该有一个函数set_name()或类似的东西:
However, I was told this was not best practice? That I should have a function set_name() or something similar like this:
function set_name($name)
{
$this->name=$name;
}
这正确吗?
如果在此示例中,我想在数据库中插入一个新的人"记录,那么如何将有关人的所有信息(即$ name,$ age,$ address,$ phone等)传递给该类,以便插入它,我应该这样做:
If in this example I want to insert a new "person" record into the db, how do I pass all the information about the person ie $name, $age, $address, $phone etc to the class in order to insert it, should I do:
function set($data)
{
$this->name= $data['name'];
$this->age = $data['age'];
etc
etc
}
然后发送一个数组?这是最佳做法吗?还是有人可以推荐最佳做法?
Then send it an array? Would this be best practice? or could someone please recommend best practice?
推荐答案
为对象的属性使用显式getter和setter(例如您为set_name
给出的示例),而不是直接访问它们会给您(除其他外)具有以下优点:
Using explicit getters and setters for properties on the object (like the example you gave for set_name
) instead of directly accessing them gives you (among others) the following advantages:
- 您可以更改内部"实现,而无需修改任何外部调用.这种外部"代码不需要经常更改(因为您提供了一致的访问方式).
- 您非常明确地提供了要在类外部使用/调用的属性.如果其他人开始使用您的课程,这将非常有用.
以上原因是为什么这样做虽然不是真正不必要的原因,但仍可以被认为是最佳实践(并且在某些用途中可能被认为是过大的;例如,当您的对象很少进行处理"时) ",但仅充当数据"的占位符.)
The above reasons is why this could be considered best practice although it's not really necessary to do so (and could be considered overkill for some uses ; for example when your object is doing very little 'processing' but merely acts as a placeholder for 'data').
这篇关于面向对象的PHP最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!