Prev | Current Page 251 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


PHP recognizes constructors by the name __construct. The general syntax for
constructor declaration follows:
function __construct([argument1, argument2, ..., argumentN])
{
// Class initialization code
}
As an example, suppose you want to immediately populate certain book fields with
information specific to a supplied ISBN. For example, you might want to know the
title and author of a book, in addition to how many copies the library owns and how
many are presently available for loan. This code might look like this:
class Book
{
private $title;
private $isbn;
private $copies;
public function _construct($isbn)
{
$this->setIsbn($isbn);
$this->getTitle();
$this->getNumberCopies();
}
public function setIsbn($isbn)
{
$this->isbn = $isbn;
}
184 CHAPTER 6 ?–  O BJECT-ORIENTED PHP
public function getTitle() {
$this->title = "Beginning Python";
print "Title: ".$this->title."
";
}
public function getNumberCopies() {
$this->copies = "5";
print "Number copies available: ".$this->copies."
";
}
}
$book = new book("159059519X");
?>
This results in the following:
Title: Beginning Python
Number copies available: 5
Of course, a real-life implementation would likely involve somewhat more intelligent
get methods (e.g., methods that query a database), but the point is made. Instantiating
the book object results in the automatic invocation of the constructor, which in turn
calls the setIsbn(), getTitle(), and getNumberCopies() methods.


Pages:
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263