13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

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

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

170 Chapter 6 Object-Oriented <strong>PHP</strong><br />

class B extends A<br />

{<br />

function __construct()<br />

{<br />

$this->operation1();<br />

$this->operation2();<br />

$this->operation3();<br />

}<br />

}<br />

$b = new B;<br />

?><br />

This code creates one operation of each type in class A: public, protected, <strong>and</strong><br />

private. B inherits from A. In the constructor of B, you then try to call the operations<br />

from the parent.<br />

The line<br />

$this->operation1();<br />

produces a fatal error as follows:<br />

Fatal error: Call to private method A::operation1() from context ‘B’<br />

This example shows that private operations cannot be called from a child class.<br />

If you comment out this line, the other two function calls will work.The protected<br />

function is inherited but can be used only from inside the child class, as done here. If<br />

you try adding the line<br />

$b->operation2();<br />

to the bottom of the file, you will get the following error:<br />

Fatal error: Call to protected method A::operation2() from context ‘’<br />

However, you can call operation3() from outside the class, as follows:<br />

$b->operation3();<br />

You can make this call because it is declared as public.<br />

Overriding<br />

In this chapter, we have shown a subclass declaring new attributes <strong>and</strong> operations. It is<br />

also valid <strong>and</strong> sometimes useful to redeclare the same attributes <strong>and</strong> operations.You<br />

might do this to give an attribute in the subclass a different default value to the same<br />

attribute in its superclass or to give an operation in the subclass different functionality to<br />

the same operation in its superclass.This action is called overriding.

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

Saved successfully!

Ooh no, something went wrong!