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

search for in the

Клонирование объектов> <Магические методы
Last updated: Fri, 05 Sep 2008

view this page in

Ключевое слово "final"

Разместив перед объявлениями методов или свойств класса ключевое слово "final", вы можете предотвратить их переопределение в дочерних классах.

Пример #1 Пример окончательных (final) методов

<?php
class BaseClass {
   public function 
test() {
       echo 
"Вызван метод BaseClass::test()\n";
   }
   
   final public function 
moreTesting() {
       echo 
"Вызван метод BaseClass::moreTesting()\n";
   }
}

class 
ChildClass extends BaseClass {
   public function 
moreTesting() {
       echo 
"Вызван метод ChildClass::moreTesting()\n";
   }
}
// Выполнение заканчивается фатальной ошибкой: Cannot override final method BaseClass::moreTesting()
// (Метод BaseClass::moretesting() не может быть переопределён)
?>


add a note add a note User Contributed Notes
Ключевое слово "final"
willekee at NOSPAM dot example dot com
22-Aug-2008 12:50
the word 'static' should have been 'final' in the text
'remember that if you defined a private static method, you cannot place method with the same name in child class.'
slorenzo at clug dot org dot ve
31-Oct-2007 03: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 05: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 static method, you cannot place method with the same name in child class.

 
show source | credits | sitemap | contact | advertising | mirror sites