PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Clonage d'objets> <Méthodes magiques
Last updated: Fri, 20 Jun 2008

view this page in

Mot-clé "final"

PHP 5 introduit le mot-clé "final" qui empêche les classes filles de surcharger une méthode en en préfixant la définition par le mot-clé "final". Si la classe elle-même est définie comme finale, elle ne pourra pas être étendue.

Exemple #1 Exemple de méthode finale

<?php
class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() appelé\n";
   }
   
   final public function 
moreTesting() {
       echo 
"BaseClass::moreTesting() appelé\n";
   }
}

class 
ChildClass extends BaseClass {
   public function 
moreTesting() {
       echo 
"ChildClass::moreTesting() appelé\n";
   }
}
// Résultat : Fatal error: Cannot override final method BaseClass::moreTesting()
?>

Exemple #2 Exemple de classe finale

<?php
final class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() appelé\n";
   }

   
// Ici, peut importe si vous spécifiez la fonction en finale ou pas
   
final public function moreTesting() {
       echo 
"BaseClass::moreTesting() appelé\n";
   }
}

class 
ChildClass extends BaseClass {
}
// Résultat : Fatal error: Class ChildClass may not inherit from final class (BaseClass)
?>


add a note add a note User Contributed Notes
Mot-clé "final"
slorenzo at clug dot org dot ve
31-Oct-2007 08: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 10: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.

Clonage d'objets> <Méthodes magiques
Last updated: Fri, 20 Jun 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites