该类,只能被实例化对象不能用于被继承。
设计时,该类不能再扩展了,就应该通过语法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);
Php面向对象 – Final类