php - “对私有(private)方法的 fatal error 调用”但方法受到保护

标签 php oop

第一次在 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!

DEMO.

关于php - “对私有(private)方法的 fatal error 调用”但方法受到保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11752327/

相关文章:

php - Spotify iFrame 无法在 Bootstrap 模态中正确显示?

php - 检测伪造的 pagerank

perl - 如何在 Perl 中取消祝福对象?

php - 在 sendgrid 电子邮件中的电子邮件内容中包含我的 html 代码

php - 使用 php 在页面上时激活类

c++ - 缺少类方法时出现奇怪的错误消息

python - python内部类的目的是什么?

oop - 我们应该总是多态而不是枚举吗?

php - javascript/php - 将 amazon awis 示例从 php 移植到 javascript

c++ - 错误 C2280。试图引用已删除的函数。尝试从数据结构中删除敌人和激光时出现此错误