05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Within a method, the $this variable contains a reference to the object on which the<br />

method was called. For instance, if you call $rasmus->birthday( ), inside the<br />

birthday( ) method, $this holds the same value as $rasmus. Methods use the $this<br />

variable to access the properties of the current object and to call other methods on<br />

that object.<br />

Here’s a simple class definition of the Person class that shows the $this variable in<br />

action:<br />

class Person {<br />

var $name;<br />

function get_name ( ) {<br />

return $this->name;<br />

}<br />

function set_name ($new_name) {<br />

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

}<br />

}<br />

As you can see, the get_name( ) and set_name( ) methods use $this to access and set<br />

the $name property of the current object.<br />

There are no keywords or special syntax for declaring a static method. A static<br />

method simplydoesn’t use $this, because the method is called on a class and not on<br />

an object. For example:<br />

class HTML_Stuff {<br />

function start_table( ) {<br />

echo "\n";<br />

}<br />

function end_table ( ) {<br />

echo "\n";<br />

}<br />

}<br />

HTML_Stuff->start_table( );<br />

// print HTML table rows and columns<br />

HTML_Stuff->end_table( );<br />

Declaring Properties<br />

In the previous definition of the Person class, we explicitlydeclared the $name property.<br />

Property declarations are optional and are simply a courtesy to whoever maintains<br />

your program. It’s good <strong>PHP</strong> style to declare your properties, but you can add<br />

new properties at any time.<br />

Here’s a version of the Person class that has an undeclared $name property:<br />

class Person {<br />

function get_name ( )<br />

{<br />

return $this->name; }<br />

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