PHP/Class/final — различия между версиями

Материал из Web эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 07:00, 26 мая 2010

Declaring Final Classes and Methods

 
<?php
     final class NoExtending {
          public function myFunction() {
          }
     }
     class restrictedExtending {
          final public function anotherFunc() {
          }
     }
     class myChild extends restrictedExtending {
          public function thirdFunction() {
          }
     }
?>



final class

<?php
final class Checkout {
    // ...
}
class IllegalCheckout extends Checkout {
    // ...
}
$checkout = new Checkout();
?>



final keyword can be used to declare a class uninheritable

 
<?
    final class Dog {
            private $Name;
            public function getName( ) {
                    return $this->Name;
            }
    }
    class Poodle extends Dog {
            public function bark( ) {
                    print ""Woof", says " . $this->getName( );
            }
    }
?>



Final Methods

 
class Item {
  private $id = 555;
  final function getID() {
    return $this->id;
  }
}

class PriceItem extends Item {
  function getID() {
    return 0;
  }
}
It generates the following error:
Fatal error: Cannot override final method item::getid()



The final keyword is used to declare that a method or class cannot be overridden by a subclass

 
<?
    class Dog {
            private $Name;
            private $DogTag;
            final public function bark( ) {
                    print "Woof!\n";
            }
    }
?>