25.09.2014 Views

ZEND PHP 5 Certification STUDY GUIDE

Create successful ePaper yourself

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

116 ” Object Oriented Programming in <strong>PHP</strong><br />

}<br />

$a = new a();<br />

$b = new b();<br />

$c = new c();<br />

$d = new d();<br />

$a->test(); // Outputs "a::test called"<br />

$b->test(); // Outputs "b::test called"<br />

$b->func(); // Outputs "a::func called"<br />

$c->test(); // Outputs "b::test called"<br />

$d->test(); // Outputs "b::test called"<br />

In this script, we start by declaring a class called a. We then declare the class b, which<br />

extends a. As you can see, this class also has a test() method, which overrides the<br />

one declared in a, thus outputting b::test called. Note, however, that we can still<br />

access a’s other methods—so that calling $b->func() effectively executes the function<br />

in the a class.<br />

Naturally, extending objects in this fashion would be very limiting, since you<br />

would only be able to override the functionality provided by parent classes, without<br />

any opportunity for reuse (unless you implement your methods using different<br />

names). Luckily, parent classes can be accessed using the special parent:: namespace,<br />

as we did for class c above; you can also access any other ancestor classes by<br />

addressing their methods by name—like we did, for example, in class d.<br />

Class Methods and Properties<br />

As we mentioned earlier, classes can contain both methods and variables (properties).<br />

Methods are declared just like traditional functions:<br />

Licensed to 482634 - Amber Barrow (itsadmin@deakin.edu.au)<br />

class myClass {<br />

function myFunction() {<br />

echo "You called myClass::myFunction";<br />

}<br />

}<br />

From outside the scope of a class, its methods are called using the indirection operator<br />

->:

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

Saved successfully!

Ooh no, something went wrong!