【问题标题】:PHP - call to member function on null [duplicate]PHP - 在 null 上调用成员函数 [重复]
【发布时间】:2016-05-22 06:29:16
【问题描述】:

我有以下三个类:

class Dom_Form_Section extends Dom {

  /* ... code ommited ... */

  public function addElem($Elem) {
      if (is_a($Elem, 'Dom_Form_Elem')) $FormElem=$Elem;
      else $FormElem=Dom_Form_Elem::create(array(), $Elem);

      if ($FormElem !== false) $this->FormElems[]=$FormElem;

      return $FormElem;
  }
}

class Dom_Form extends Dom {

   private $FormSections=array();

   /* ... code ommited ... */

   public function addElem($Elem) {
    if (is_a($Elem, 'Dom_Form_Elem')) $FormElem=$Elem;
    else $FormElem=Dom_Form_Elem::create(array(), $Elem);

    if ($FormElem !== false) {
        if (empty($this->FormSections)) $Section=$this->addSection();
        else $Section=$this->FormSections[count($this->FormSections)];
        return $Section->addElem($FormElem); // !!! this is where the error fires
    } else return false;
   }

   public function addSection($SectionData=array()) {
    $id=$this->FormId."-section-".count($this->FormSections);

    if (!is_array($SectionData)) $SectionData=array();
    $FormSection=new Dom_Form_Section($SectionData, $id);
    $this->FormSections[]=$FormSection;

    return $FormSection;

 }
}

class Dom_Form_Elem extends Dom {

  public static function create($data, $Elem) {
    if (!is_a($Elem, 'Dom')) return false;
    else {
       $FormElem=new Dom_Form_Elem($data, $Elem);
       return $FormElem;
    }
  }

  /* ... code ommited ... */
}

如果我运行以下代码:

 $Form=new Dom_Form();
 $Form->addElem($Input); // $Input is of 'Dom'

我收到以下错误:

Fatal error: Call to a member function addElem() on null

如果我在两个addElem 函数中包含一些回声(Dom_Form_Section 中的一个和Dom_Form 中的一个)它们都会触发,但错误仍然存​​在。在我看来,好像我在某个地方创建了一个循环,这就是我收到错误的原因。

另外,如果我 var_dump $Section 变量的内容,就在错误触发之前,它是一个有效的 Dom_Form_Section 对象。当我尝试调用 Dom_Form_Section::addElem() 方法时会触发错误。

代码有什么问题?

编辑:
在@A-2-A 的帮助下,我发现问题出在这一行:

else $Section=$this->FormSections[count($this->FormSections)];

我尝试访问 $this->FormSections 数组的未声明成员。通过将count($this->FormSections) 更改为count($this->FormSections)-1,代码现在可以正常工作了。

【问题讨论】:

  • 你有什么错误吗?在php日志还是显示?
  • de Dom 类中有什么?你在 new Dom_Form(); 行上没有收到任何错误吗?
  • 不,错误在调用Dom_Form_Section::addElem() 方法之前触发。显示的确切错误如下:Fatal error: Call to a member function addElem() on null in /location/of/the/Dom_Form/class/file/ on line 57错误被触发的确切位置
  • Domclass 中有什么?在<?php 之后的页面顶部添加error_reporting(E_ALL);ini_set('display_errors',1); 并检查您还遇到了什么错误?
  • 鉴于问题没有包含足够的信息来诊断问题,并且 OP 在发现问题后也没有给出解决方案,因此这个问题对于任何未来的访问者来说都毫无价值。

标签: php


【解决方案1】:

不清楚您在Dom 类中的内容。所以要弄清楚这个问题对我们所有人来说都有些困难。

请将此代码添加到您的文件中以检查所有错误,并且您可能能够自己获得解决方案。

<?php
error_reporting(-1);
ini_set('display_errors', 1);

........ rest of your code

注意:请将此代码添加到文件顶部 &lt;?php 之后,正如我向您展示的那样。

【讨论】:

    猜你喜欢
    • 2015-10-26
    • 2017-02-23
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2017-12-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多