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.

You can use variable variables with property names:<br />

$prop = 'age';<br />

echo $rasmus->$prop;<br />

A static method is one that is called on a class, not on an object. Such methods cannot<br />

access properties. The name of a static method is the class name, followed by<br />

two colons and the function name. For instance, this calls the p( ) method in the<br />

HTML class:<br />

HTML::p("Hello, world");<br />

A class’s documentation tells you which methods are static.<br />

Assignment creates a copyof an object with identical properties. Changing the copy<br />

does not change the original:<br />

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

$b = $f; // make a copy<br />

$b->set_name('Barney'); // change the copy<br />

printf("%s and %s are best friends.\n", $b->get_name(), $f->get_name( ));<br />

Barney and Fred are best friends.<br />

Declaring a Class<br />

To design your program or code library in an object-oriented fashion, you’ll need to<br />

define your own classes, using the class keyword. A class definition includes the<br />

class name and the properties and methods of the class. Class names are case-insensitive<br />

and must conform to the rules for <strong>PHP</strong> identifiers. The class name stdClass is<br />

reserved. Here’s the syntax for a class definition:<br />

class classname [ extends baseclass ]<br />

{<br />

[ var $property [ = value ]; ... ]<br />

}<br />

[ function functionname (args) {<br />

// code<br />

}<br />

...<br />

]<br />

Declaring Methods<br />

A method is a function defined inside a class. Although <strong>PHP</strong> imposes no special<br />

restrictions, most methods act onlyon data within the object in which the method<br />

resides. Method names beginning with two underscores (__) maybe used in the<br />

future by<strong>PHP</strong> (and are currentlyused for the object serialization methods _ _sleep( )<br />

and _ _wakeup( ), described later in this chapter), so it’s recommended that you do<br />

not begin your method names with this sequence.<br />

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

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Declaring a Class | 143

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

Saved successfully!

Ooh no, something went wrong!