The use of final keyword is just like that occurs in Java
In java final has three uses
1) prevent class Inheritance
2) prevent method overriding or redifination of
method in subclass
3) and to declare constants
But the third point seems to be missing from the PHP
I guess, as i am a java developer Currently gaining competence in PHP
Ключова дума final
В PHP 5 е въведена ключовата дума final, като използването й пред дефиницията на метод от родителски клас предотвратява възможността този метод да бъде дефиниран повторно в дъщерен клас. Ако даден клас е дефиниран като final, то той не може да бъде наследяван.
Example #1 Пример за final метод
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called\n";
}
}
// Резултатът ще е Fatal error: Cannot override final method BaseClass::moreTesting()
?>
Example #2 Пример за final клас
<?php
final class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
// Тук няма значение дали методът ще е final или не
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
}
// Резултатът ще е Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>
Ключова дума final
santoshjoshi2003 at yahoo dot co dot in
05-Dec-2008 12:45
05-Dec-2008 12:45
slorenzo at clug dot org dot ve
31-Oct-2007 09:13
31-Oct-2007 09:13
<?php
class parentClass {
public function someMethod() { }
}
class childClass extends parentClass {
public final function someMethod() { } //override parent function
}
$class = new childClass;
$class->someMethod(); //call the override function in chield class
?>
penartur at yandex dot ru
22-Mar-2007 11:39
22-Mar-2007 11:39
Note that you cannot ovverride final methods even if they are defined as private in parent class.
Thus, the following example:
<?php
class parentClass {
final private function someMethod() { }
}
class childClass extends parentClass {
private function someMethod() { }
}
?>
dies with error "Fatal error: Cannot override final method parentClass::someMethod() in ***.php on line 7"
Such behaviour looks slight unexpected because in child class we cannot know, which private methods exists in a parent class and vice versa.
So, remember that if you defined a private final method, you cannot place method with the same name in child class.
