这可能是一个基本问题,但是我会按照本教程进行操作,并且在某一时刻代码看起来像这样。
<?php
class person
{
public $name;
public $height;
protected $social_security_no;
private $pin_number = 3242;
public function __construct($person_name)
{
$this->name = $person_name;
}
public 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
{
public 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()函数中添加保护时,但是在我看来,这是本教程中重写的首选方法。有任何想法吗?
最佳答案
“问题似乎出在我将protected
添加到雇员类的get_name()
函数中时” –这就是您的答案。 protected 方法只能从完全相同的类或子类中调用,而不能“从外部”调用。如果要以这种方式使用它,则该方法必须是公开的。
关于php - 为什么我不能在PHP中调用此 protected 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19276734/