2013-10-09 24 views
1

这可能是一个基本的问题,但即时通讯本教程后,在一个点上代码看起来像这样。为什么我不能在PHP中重写这个受保护的函数?

<?php 

class person { 
var $name; 
public $height; 
protected $social_security_no; 
private $pin_number = 3242; 

function __construct($person_name){ 
    $this->name = $person_name; 
} 
function set_name($new_name){ 
    $this->name = $new_name; 
} 

protected function get_name() { 
    return $this->name; 
} 

public function get_pin_number_public() { 
    $this->pub_pin = $this->get_pin_number(); 
    return $this->pub_pin; 
} 

private function get_pin_number() { 
    return $this->pin_number; 
} 


} 

class employee extends person { 

function __construct($person_name){ 
    $this->name = $person_name; 
} 

protected function get_name() { 
    return $this->name; 
} 
} 

然而,当我使用这个

<?php include("class_lib.php"); ?> 
</head> 
<body id="theBody"> 
<div> 

<?php 
$maria = new person("Default"); 

$dave = new employee("David Knowler"); 
echo $dave->get_name(); 

?>

我得到这个错误

Fatal error: Call to protected method employee::get_name() from context '' in C:\Users\danny\Documents\Workspace\test\index.php on line 13 

的问题似乎是当我添加受保护的GET_NAME()函数在雇员类中,但在我看来,这是在教程中重写的首选方式。有任何想法吗?

+0

保护的方法不能被称为类 –

回答

2

“问题似乎是当我将protected添加到雇员类中的get_name()函数” - 这是您的答案。受保护的方法只能从相同的类或子类调用,而不能从“外部”调用。如果你想以这种方式使用它,你的方法必须是公开的。

+0

外面我必须给你鉴定,我的答案是多比的原因如何。尽管每个人都会获得有用的信息。谢谢 – lorless

1

问题不是你无法重写受保护的方法,而是你从类外部调用受保护的方法。

在类被实例化之后,您可以调用一个公共方法,该方法又可以调用get_name(),您将看到该代码将按预期工作。

例如:

class employee extends person { 

    function __construct($person_name){ 
     $this->name = $person_name; 
    } 

    protected function get_name() { 
     return $this->name; 
    } 

    public function name() 
    { 
     return $this->get_name(); 
    } 
} 

$dave = new employee("David Knowler"); 
echo $dave->name(); 

在你的榜样,你很可能是最好做get_name()公众。

相关问题