';对私有方法';的致命错误调用;但是方法是受保护的


'Fatal error call to private method' but method is protected

第一次在PHP中扩展一个类时,我遇到了一个致命的错误,说该方法是私有的,而不是私有的。我确信这是一些初级的东西,但我研究过书籍和论坛,我只是无法确定我做了什么来产生这个错误。非常感谢您的帮助。详细信息如下:

错误消息:

致命错误:从第726行/root/included/classes/testprinter.php中的上下文"testprinter"调用私有方法testgiver::dbConnect()

下面代码中测试打印机的第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 methods,但不仅不能从protected方法,而且不能从类示例访问private方法。要从subclass的实例访问parent classprotected方法,您可以在子类中声明public method,然后从子类的公共方法调用parent classprotected method,即

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!

演示

您不能从类实例访问受保护的方法。阅读说明Members declared protected can be accessed only within the class itself and by inherited and parent classes

的文档

阿尔法,伟大的写作!

我觉得我几乎已经把它拿到了我想要的地方,但正在得到

Fatal Error, call to undefined method NameofClass::myFunction() in line 123456

我这里缺了什么吗?

我的原始类和扩展类都在同一个.php文件中,但对myFunction的调用发生在另一个文件中。这是不允许的吗?

注意:我会把它放在评论中,但系统不允许我包括评论,直到我的声誉达到50。