第一次在 PHP 中扩展一个类时,我收到一个 fatal error ,提示该方法是私有(private)的,而实际上它不是。我确定这是基本的东西,但我已经研究过书籍和论坛,但我无法确定我做了什么来产生这个错误。非常感谢任何帮助。详情如下:
错误信息:
Fatal error: Call to private method testgiver::dbConnect() from context 'testprinter' in /root/includes/classes/testprinter.php on line 726
下面代码中testprinter的第726行:
private function buildquestionarray()
{
$query = "etc etc";
**$conn = $this->dbConnect('read');
$result = $conn->query($query);
...
Testprinter 扩展了 testgiver。这是类的扩展:
require_once('testgiver.php');
class testprinter extends testgiver
{...
以及testgiver中方法的声明:
protected function dbConnect($userconnecttype)
{...
再次感谢!
最佳答案
正如 Alexander Larikov
所说,您不能从类实例访问 protected 方法
,不仅是 protected
方法,而且您也可以'从类实例访问 private
方法。要从子类
的实例访问父类
的protected
方法,您需要在子类,然后从子类的公共(public)方法调用父类
的保护方法
,即
class testgiver{
protected function dbConnect($userconnecttype)
{
echo "dbConnect called with the argument ".$userconnecttype ."!";
}
}
class testprinter extends testgiver
{
public function buildquestionarray() // public instead of private so you can call it from the class instance
{
$this->dbConnect('read');
}
}
$tp=new testprinter();
$tp->buildquestionarray(); // output: dbConnect called with the argument read!
关于php - “对私有(private)方法的 fatal error 调用”但方法受到保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11752327/