Php面向对象 ? Final类

WBOY
Freigeben: 2016-06-23 13:51:18
Original
1089 Leute haben es durchsucht

Php面向对象 ? Final类

 

该类,只能被实例化对象不能用于被继承。

设计时,该类不能再扩展了,就应该通过语法final限制,其他用户扩展该类。

 

定义:

在class前,增加final关键字。

 

例子:

class Goods

{

       public  $goods_name;

       public  $shop_price;

       public  function __construct($name,$price)

       {

              $this->goods_name= $name;

              $this->shop_price= $price;

       }

}

 

final class GoodsBook  extends Goods

{

       public $pages;

       public  function __construct($name,$price,$pages)

       {

              parent::__construct($name,$price);

              $this->pages= $pages;

       }

}

 

 

$book1 = new  GoodsBook(‘php’,234,56,45);

 

 

Final 关键字的另一个用法,用于限制方法:

限制该方法,在所属类被继承时,该方法不能被重写。

 

 

 

例子:

 

 

class Goods

{

       public  $goods_name;

       public  $shop_price;

       public  function __construct($name,$price)

       {

              $this->goods_name= $name;

              $this->shop_price= $price;

       }

      

       public  function  sayName()

       {

              echo  $this->goods_name;

       }

      

       //所有商品输出价格的方式应该一致

       final  public  function sayPrice()    // 继承该类,该方法不能被重写

       {

              echo ‘¥’,$this->shop_price;

       }

}

 

final class GoodsBook  extends Goods

{

       public $pages;

       public  function __construct($name,$price,$pages)

       {

              parent::__construct($name,$price);

              $this->pages= $pages;

       }

 

       public  function sayName()

       {

              echo“《 $this->goods_name 》”;

       }

}

 

$book1 = new  GoodsBook(‘php’,234,56,45);

 

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!