13.09.2016 Views

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

Create successful ePaper yourself

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

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

In the same way that providing new attributes or operations in a subclass does not affect<br />

the superclass, overriding attributes or operations in a subclass does not affect the superclass.<br />

A subclass will inherit all the attributes <strong>and</strong> operations of its superclass, unless you<br />

provide replacements. If you provide a replacement definition, it takes precedence <strong>and</strong><br />

overrides the original definition.<br />

The parent keyword allows you to call the original version of the operation in the<br />

parent class. For example, to call A::operation from within class B, you would use<br />

parent::operation();<br />

The output produced is, however, different. Although you call the operation from the<br />

parent class, <strong>PHP</strong> uses the attribute values from the current class. Hence, you get the following<br />

output:<br />

Something<br />

The value of $attribute is different value<br />

Inheritance can be many layers deep.You can declare a class imaginatively called C that<br />

extends B <strong>and</strong> therefore inherits features from B <strong>and</strong> from B’s parent, A.The class C can<br />

again choose which attributes <strong>and</strong> operations from its parents to override <strong>and</strong> replace.<br />

Preventing Inheritance <strong>and</strong> Overriding with final<br />

<strong>PHP</strong> uses the keyword final.When you use this keyword in front of a function declaration,<br />

that function cannot be overridden in any subclasses. For example, you can add it<br />

to class A in the previous example, as follows:<br />

class A<br />

{<br />

public $attribute = "default value";<br />

final function operation()<br />

{<br />

echo "Something";<br />

echo "The value of \$attribute is ". $this->attribute."";<br />

}<br />

}<br />

Using this approach prevents you from overriding operation() in class B. If you attempt<br />

to do so, you will get the following error:<br />

Fatal error: Cannot override final method A::operation()<br />

You can also use the final keyword to prevent a class from being subclassed at all.To<br />

prevent class A from being subclassed, you can add it as follows:<br />

final class A<br />

{...}<br />

If you then try to inherit from A, you will get an error similar to<br />

Fatal error: Class B may not inherit from final class (A)

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

Saved successfully!

Ooh no, something went wrong!