使用类的构造函数的正确方法是让它设置好可以使用的类。在许多情况下,构造函数除了接受依赖项(例如数据库对象)之外并没有做太多事情,并保存这些以供以后使用。
(Ab) 使用您在第一个示例中所做的构造函数会导致许多困难,主要是因为简单地创建对象除了创建所述对象之外还有其他副作用。
以这种方式,您的第二个示例更接近于真正的面向对象编程,即使您仍然没有真正利用使用类为您提供的任何东西。事实上,将其编写为纯过程代码会更好。
虽然我不知道您的代码做了什么,但我尝试了一个示例,利用类的特性为您提供:
/**
* We need a DB connection in case we need to get something from the database.
* This is called a dependency, and we save it in the object at object creation time.
*
* Nothing that causes the object itself to do "work" is supposed to be here, only things
* necessary for actually creating the object in a state where we can _start_ working with it.
*
* @param PDO $db
*/
public function __construct (PDO $db) {
$this->db = $db;
}
/**
* Sets the value for each step. Legal values for $step is between 1 and 3, inclusive.
* Normally we'd have many setters, one for each property we want to change from outside.
* That can be anything from address to price and anything else one can think of.
*
* @param int $step
* @param int|string $value
*
* @throws InvalidArgumentException
* @return void
*/
public function set_value ($step, $value) {
if ($step <= 0 || $step > 3) {
throw new InvalidArgumentException("Step must be between 1 and 3, inclusive.");
}
$this->value[$step] = $value;
}
/**
* This is where the actual processing is done.
* In a normal class there would be several such functions
* each doing one specific thing (creating a new record, saving
* it to the database, validating stuff, etc).
*
* @return void
*/
public function do_processing () {
$this->result = implode(", ", $this->data);
}
/**
* Fetches the result of the class. Normally we have many getters, which return
* one part of the data associated with the object. Such as username, hash, email, etc.
*
* These are often in a 1-1 relationship with setters.
*
* @return string
*/
public function get_result () {
// If we have no calculated result, fetch it from the DB instead.
if (empty($this->result)) {
return $this->db->get_cached_result ();
}
// Returns the newly calculated result.
// Should probably also cache it, to make the above line useful.
return $this->result;
}
}
// A DB interface class, which extends PDO.
$db = new MyClassDB ();
$obj = new MyClass ($db);
$obj->set_value (2, "Two");
$obj->set_value (1, "One");
$obj->set_value (3, "Three");
$obj->do_processing();
echo $obj->get_result();
请注意,这是一个非常简单的类,并不能很好地帮助您了解如何正确利用类。我建议查看更充实的类,您可以在任何主要框架中找到它。