【问题标题】:'Fatal error call to private method' but method is protected'对私有方法的致命错误调用'但方法受到保护
【发布时间】:2017-07-23 21:07:52
【问题描述】:

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

错误信息:

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

下面代码中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)
{...

再次感谢!

【问题讨论】:

    标签: php oop


    【解决方案1】:

    正如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!
    

    DEMO.

    【讨论】:

    • 我认为你有一个类型 “你不能从类实例访问 protected 方法,而不仅仅是 protected 方法”我>
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      Alpha,写得很棒!

      我觉得我已经快到我想要的地方了,但我正在得到它

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

      这里有什么我遗漏的吗?

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

      注意:我会将此放在评论中,但系统不会让我包含 cmets,直到我的声誉达到 50。

      【讨论】:

        猜你喜欢
        • 2011-07-09
        • 2012-01-09
        • 1970-01-01
        • 2014-12-21
        • 2013-01-18
        • 2019-02-10
        • 2022-08-05
        • 2014-03-05
        • 2011-06-14
        相关资源
        最近更新 更多