我只是掌握了OOP PHP,虽然我已经明白了,但我对final
关键字有些麻烦。书中说,Final
会停止子类方法,覆盖超类方法。下面我试过了,我的IDE显示了一些错误,但它不起作用。我看了看,但书中说这应该是超类方法而不是子类。
$object=new userprofile();
$object->name="Mike";
$object->age=22;
$object->sex="Male";
//2 properties of subclass
$object->email="username@domain.com";
$object->website="http://domain.com";
echo $object->get_name(); //method call
class user{
public $name, $age, $sex;
final function get_name(){
return "Not overriden";
}
}
class userprofile extends user{
public $email,$website;
function get_name(){
return $this->website;
}
}
答案 0 :(得分:1)
正如错误消息所示,您无法定义一个方法来覆盖已标记为final的方法。你甚至不被允许尝试(为什么你会这样,因为新方法不会产生任何影响)。
另请参阅第一个示例中描述的documentation for the final keyword。
答案 1 :(得分:1)
听起来你回答了自己。通过在基类上定义final
关键字,您无法在子类中覆盖它。删除final
关键字以覆盖它。