class Foo {
public function __construct() {
print("This is called when a new object is created");
// Good to use when you need to set initial values,
// (possibly) create a connection to a database or such.
}
public function __destruct() {
print("This is called when the class is removed from memory.");
// Should be used to clean up after yourself, close connections and such.
}
}
$foo = new Foo();
添加,
class Person {
private $name; // Instance variable
private $status; // Instance variable
// This will be called when a new instance of this class i created (constructed)
public function __construct($name, $age) {
$this->name = ucfirst($name); // Change input to first letter uppercase.
// Let the user of our class input something he is familiar with,
// then let the constructor take care of that data in order to fit
// our specific needs.
if ($age < 20) {
$this->status = 'Young';
} else {
$this->status = 'Old';
}
}
public function printName() {
print($this->name);
}
public function printStatus() {
print($this->status);
}
}
$Alice = new Person('alice', 27);
$Alice->printName();
$Alice->printStatus();
/添加
如果您运行上述代码并阅读注释,您应该能够理解何时以及如何使用构造函数和析构函数。