PHP 面向对象OOP开发中的关键字 final , static , const , instanceof
final 关键字
出于安全考虑,被final修饰的类无法继承,被final修饰的方法无法被重写,关键字final只能用来修饰类和方法。
class parentClass{
final public function show(){
echo "This is a class named parentClass";
}
}
class childClass extends parentClass{
public function show(){
echo "This is a class named childClass";
}
}
childClass::show();
/*
#
# final 关键字只能用来修饰类和方法,final 修饰的类不能被继承,
# final 修饰的方法不能被重写
#
*/
以上代码输出:
Fatal error: Cannot override final method parentClass::show() in *_class.php on line 17
static 关键字
static 可以用来修饰成员属性和成员方法,以声明该属性和方法为静态,静态属性和静态方法不需要实例化即可访问,访问方法为类名::$静态属性|静态方法()
。
在类的内部引用静态属性和静态方法时,不可使用$this->$属性|方法()
,而应该使用self::$属性|方法()
。换句话说,如果类中的成员属性和成员方法使用了static修饰的话,如果需要在类的其他方法中引用它们,就必须使用self::$属性|方法()
来调用。
const 关键字
如果需要在类的内部定义常量,则需要使用const关键字,其基本语法是 const CONSTANT = 'CONSTANT VALUE';
。在类的内部访问常量则需要定义专有方法,在类的外部访问常量和访问及静态属性类似,只要使用类名::CONSTANT
即可。
instanceof 关键字
这个关键字用来判断当前对象是否是某个类实例化而来,其基本语法是 $obj instanceof Class
,会返回一个布尔结果。