Home > Backend Development > PHP Tutorial > Php面向对象 ? Final类

Php面向对象 ? Final类

WBOY
Release: 2016-06-23 13:51:18
Original
1145 people have browsed it

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);

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template