Page 248 - Beginning PHP 5.3
P. 248
Part II: Learning the Language
You can also pass arguments to constructors, just like normal methods. This is great for setting certain
properties to initial values at the time the object is created. The following example shows this principle
in action:
class Person {
private $_firstName;
private $_lastName;
private $_age;
public function __construct( $firstName, $lastName, $age ) {
$this- > _firstName = $firstName;
$this- > _lastName = $lastName;
$this- > _age = $age;
}
public function showDetails() {
echo “$this- > _firstName $this- > _lastName, age $this- > _age < br / > ”;
}
}
$p = new Person( “Harry”, “Walters”, 28 );
$p- > showDetails(); // Displays “Harry Walters, age 28”
The Person class contains three private properties and a constructor that accepts three values,
setting the three properties to those values. It also contains a showDetails() method that displays
the property values. The code creates a new Person object, passing in the initial values for the three
properties. These arguments get passed directly to the __construct() method, which then sets the
property values accordingly. The last line then displays the property values by calling the
showDetails() method.
If a class contains a constructor, it is only called if objects are created specifically from that class; if an
object is created from a child class, only the child class ’ s constructor is called. However, if necessary you
can make a child class call its parent ’ s constructor with parent::__construct() .
Cleaning Up Objects with Destructors
Destructors are useful for tidying up an object before it ’ s removed from memory. For example, if an
object has a few files open, or contains data that should be written to a database, it ’ s a good idea to close
the files or write the data before the object disappears.
You create destructor methods in the same way as constructors, except that you use __destruct()
rather than __construct() :
function __destruct() {
// (Clean up here)
}
Note that, unlike a constructor, a destructor can ’ t accept arguments.
210
9/21/09 9:03:46 AM
c08.indd 210 9/21/09 9:03:46 AM
c08.indd 210