【问题标题】:Call to a member function test1() on a non-object在非对象上调用成员函数 test1()
【发布时间】:2012-04-20 21:37:52
【问题描述】:

我对 php 还是很陌生,但我一直在尝试查找(如果可能的话)从子类调用执行不同子函数的父函数。我读过子类彼此不知道,但我认为父类可能是。

我确实已经搜索了几个小时,但我还没有找到我认为会有所帮助的东西。

以下将输出:

::dad Class initiated::
::daughter Class initiated::
::son Class initiated::

Call to a member function test1() on a non-object in ....  on line 15

代码:

class dad {  

    function dad() 
    { 
        echo '::'.get_class($this).' Class initiated::<br>';
        $this -> daughter = new daughter();
        $this -> son = new son();
    }

    public function afunction($string) {

        return $this->son->test1($string);

    }

}

class daughter extends dad {

    function daughter() {
    echo '::'.get_class($this).' Class initiated::<br>';

    }

    public function test() {

        parent::afunction("test");

    }

}

class son extends dad {

    function son() {
    echo '::'.get_class($this).' Class initiated::<br>';

    }

    public function test1($string) {

        echo $string;

    }

}


$dad = new dad(); 
$dad->daughter->test();

感谢任何/所有帮助。

【问题讨论】:

标签: php class member-functions


【解决方案1】:

这应该可以帮助你:PHP: How to call function of a child class from parent class

通常,按照您尝试的方式调用子类方法是不正确的。子类旨在扩展现有的(在大多数情况下功能齐全)类,它不应依赖于现有的子类。

【讨论】:

    【解决方案2】:

    不要使用诸如 dad() 之类的构造函数或类似的用户魔术函数 __construct() 来代替。我很确定你在爸爸班上没有可见的外地女儿。你必须定义它。

    【讨论】:

      【解决方案3】:

      长话短说:dad,daughterson 是独立的对象,调用函数形式 parent 只能在一个对象内工作。在您的示例中,daughter 不知道绑定到 dad 对象,只有它从它继承属性和方法。为了让它工作,你应该将父对象传递给孩子,让他们知道他们的父母,并在这个父对象上调用函数:

      class dad {  
          function dad(){ 
              echo '::'.get_class($this).' Class initiated::<br>';
              $this -> daughter = new daughter($this);
              $this -> son = new son($this);
          }
      
          public function afunction($string){
             return $this->son->test1($string);
          }
      }
      
      class daughter extends dad {
          function daughter($father) {
              $this->father = $father;
              echo '::'.get_class($this).' Class initiated::<br>';
          }
      
          public function test() {
              $this->father->afunction("test");
          }
      }
      
      class son extends dad {
          function son($father) {
              $this->father = $father;
              echo '::'.get_class($this).' Class initiated::<br>';
          }
      
          public function test1($string) {
              echo $string;
          }
      }
      
      $dad = new dad(); 
      $dad->daughter->test();
      

      【讨论】:

      • 你为什么建议在类之后命名构造函数的 php4 约定?应该使用__construct
      • 我没有建议,只是复制了 OP 代码,只进行了必要的更改以使其更易于理解。
      猜你喜欢
      • 2010-09-26
      • 2015-05-01
      • 2014-08-07
      • 2013-12-01
      • 2015-12-23
      • 2015-08-29
      • 2015-02-02
      • 2015-05-22
      • 2015-03-24
      相关资源
      最近更新 更多