Final classes
Inheritance allows for enormous flexibility within a class hierarchy. You can create subclasses to extend the functionality of a base class, but PHP OOP gives the posibility to create classes that cannot be extended. Such a class is called
final class.
A
final class is declared by adding the
final keyword before the
class word.
- For example:
<?php
// base class (declared final)
final class Base {
// ... PHP code
}
// define a child class derivated from Base
class BaseChild extends Base {
// ... PHP instructions
}
?>
Running this code will generate the following error:
Fatal error: Class BaseChild may not inherit from final class (Base) in ...
Final methods
A normal method (public or protected) can be overridden in the child class. If you want a method to remain fixed and unchanging, prefix the definition with the
final keyword.
A final method cannot be overridden.
- For example:
<?php
// base class
class Base {
// final method
final public function testMethod() {
echo 'This is a final method';
}
}
// define a child class derivated from Base
class BaseChild extends Base {
// override the testMethod()
public function testMethod() {
echo 'Another text';
}
}
?>
This example will generate the following error:
Fatal error: Cannot override final method Base::testMethod() in ...
By declaring a class or method final, you limit the flexibility given by inheritance, so, use final with care.
Daily Test with Code Example
HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li><ul>
<li>http://coursesweb.net/html/</li>
<li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block.some_class {
display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()var obj = {
"courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr); // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue; // CoursesWeb.net