05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

These arguments are passed to the class’s constructor, a special function that initializes<br />

the properties of the class.<br />

A constructor is a function with the same name as the class in which it is defined.<br />

Here’s a constructor for the Person class:<br />

class Person {<br />

function Person ($name, $age) {<br />

$this->name = $name;<br />

$this->age = $age;<br />

}<br />

}<br />

<strong>PHP</strong> does not provide for an automatic chain of constructors; that is, if you instantiate<br />

an object of a derived class, onlythe constructor in the derived class is automaticallycalled.<br />

For the constructor of the parent class to be called, the constructor in<br />

the derived class must explicitlycall the constructor. In this example, the Employee<br />

class constructor calls the Person constructor:<br />

class Person {<br />

var $name, $address, $age;<br />

function Person($name, $address, $age) {<br />

$this->name = $name;<br />

$this->address = $address;<br />

$this->age = $age;<br />

}<br />

}<br />

class Employee extends Person {<br />

var $position, $salary;<br />

function Employee($name, $address, $age, $position, $salary) {<br />

$this->Person($name, $address, $age);<br />

$this->position = $position;<br />

$this->salary = $salary;<br />

}<br />

}<br />

References<br />

When you assign an object to another variable, you create a copy:<br />

$fred = new Person;<br />

$copy = $fred;<br />

$fred->name("Fred");<br />

print $copy->name(); // does not print "Fred"<br />

You now have two Person objects, $fred and $copy, with independent propertyvalues.<br />

This is also the case when you assign the results of a call to a constructor, as<br />

shown here:<br />

$fred = new Person;<br />

146 | Chapter 6: Objects<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!