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.

Assuming that a Person class has been defined, here’s how to create a Person object:<br />

$rasmus = new Person;<br />

Do not quote the class name, or you’ll get a compilation error:<br />

$rasmus = new 'Person'; // does not work<br />

Some classes permit you to pass arguments to the new call. The class’s documentation<br />

should saywhether it accepts arguments. If it does, you’ll create objects like<br />

this:<br />

$object = new Person('Fred', 35);<br />

The class name does not have to be hardcoded into your program. You can supply<br />

the class name through a variable:<br />

$class = 'Person';<br />

$object = new $class;<br />

// is equivalent to<br />

$object = new Person;<br />

Specifying a class that doesn’t exist causes a runtime error.<br />

Variables containing object references are just normal variables—theycan be used in<br />

the same ways as other variables. Of particular note is that variable variables work<br />

with objects, as shown here:<br />

$account = new Account;<br />

$object = 'account'<br />

${$object}->init(50000, 1.10); // same as $account->init<br />

Accessing Properties and Methods<br />

Once you have an object, you can use the -> notation to access methods and properties<br />

of the object:<br />

$object->propertyname<br />

$object->methodname([arg, ... ])<br />

For example:<br />

printf("Rasmus is %d years old.\n", $rasmus->age); // property access<br />

$rasmus->birthday(); // method call<br />

$rasmus->set_age(21); // method call with arguments<br />

Methods are functions, so they can take arguments and return a value:<br />

$clan = $rasmus->family('extended');<br />

<strong>PHP</strong> does not have the concept of private and public methods or properties. That is,<br />

there’s no wayto specifythat onlythe code in the class should be able to directly<br />

access a particular propertyor method. Encapsulation is achieved byconvention—<br />

onlyan object’s code should directlyaccess its properties—rather than being<br />

enforced by the language itself.<br />

142 | 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!