36、PHP面向对象中的final和const的用法

阅读() @2018-10-29 18:16:06

一、final指定某个类不允许被继承或者是某个方法不允许被修改:

1、类A不允许类B继承:

final class A{
	private $name;
	private $age;
	private $height;
	function __construct($a,$b,$c){
		$this->name = $a;
		$this->age = $b;
		$this->height = $c;
	}
	final function show(){
		return $this->height;
	}
}

class B extends A{
	
}//报错: Class B may not inherit from final class (A)*/

2、类A中的方法show不允许被重写或修改:

class A{
	private $name;
	private $age;
	private $height;
	function __construct($a,$b,$c){
		$this->name = $a;
		$this->age = $b;
		$this->height = $c;
	}
	final function show(){
		return $this->height;
	}
}
$a = new A('zym','23岁','180cm');
echo $a->show();

class B extends A{
	function show(){
		return $this->name;
	}
}
$b = new B('zyy','24','172cm');
$b->show();//报错: Cannot override final method A::show()

二、const指定类常量,仅限这个类进行调用,类的实例对象也不能调用:

class A{
	private $name;
	private $sex;
	const work = 'web前端开发';
	function __construct($a,$b){
		$this->name = $a;
		$this->sex = $b;
	}
	public function show(){
		return $this->name.'的工作是'.self::work;
	}
}
$a = new A('zym','男');
echo $a->show();//zym的工作是web前端开发
微信二维码
锐壳主机