【问题标题】:Uncaught Error: Call to a member function error message未捕获的错误:调用成员函数错误消息
【发布时间】:2018-06-02 06:10:25
【问题描述】:

更新 1:

我忘了添加GetTags()方法,所以这里是:

public $blog_tags;
public function GetTags()
{
    return $this->blog_tags;
}

================================================ ============================

我正在使用 PHP OOP 开发我的项目。基本上我有一个名为blogs 的表,其中包含一些字段和数据,如下图:

capture

然后我创建了一个类Blos.class.php,并做了如下两个方法:

public function ShowTag()
{
    $tag = $this->_db->prepare("SELECT blog_tags FROM blogs");
    $tag->execute();
    while($row = $tag->fetch())
    {
        $this->blog_tags = $row['blog_tags'];
    }
}
public function NumTag()
{
    $cat = $this->_db->prepare("SELECT blog_tags FROM blogs");
    $cat->execute();
    $row_cat = $cat->rowCount();
    return $row_cat;
}

然后为了在屏幕上检索数据,我这样做了:

$tagSet = new Blogs();
$tags = $tagSet->NumTag();
$tagShow = $tagSet->ShowTag();

if(!empty($tags)){
    $tagShow->GetTags();
}else{
    echo "There is no tag available right now!";
}

但问题是我收到此错误消息:

致命错误:未捕获的错误:在第 20 行调用 null 上的成员函数 GetTags()

这是哪一行:

$tagShow->GetTags();

那有什么错误呢?你能帮帮我吗?

【问题讨论】:

    标签: php function oop


    【解决方案1】:

    类函数的问题是

    $tagShow = $tagSet->ShowTag(); //returns no value, hence $tagShow is null/empty.
    

    此外,

    $tagShow->GetTags();
    

    GetTags() 是您的类中不存在的函数。此外,您以错误的方式调用该函数。 $tagShow 原本不是你的类的对象,它是一个存储 ShowTag() 输出的变量。

    如果您有一个名为 GetTags() 的函数,请使用

    调用它
    $tagSet->GetTags();
    

    尝试以这种方式使用它:

    public function ShowTag()
    {
        $blog_tags=array();
        $tag = $this->_db->prepare("SELECT blog_tags FROM blogs");
        $tag->execute();
        while($row = $tag->fetch())
        {
            $blog_tags[] = $row['blog_tags'];
        }
    
        return $blog_tags;
    }
    

    然后在你的电话中,

    $tagShow = $tagSet->ShowTag();
    
    if(count($tagShow)>0){
        print_r($tagShow);   //Do whatever with the tags array.
    }else{
        echo "There is no tag available right now!";
    }
    

    试试这个方法,看看是否有帮助。

    【讨论】:

    • 然后它什么都没有显示,没有输出,也没有错误!但是 db 中存在一些行!
    • 你有没有在类中添加getTags()函数。如果是,请更新您的代码,以便我检查。另外,尝试从 ShowTags() 返回一些内容并打印它并查看它的输出。
    • 感谢您的回答,您所说的所有步骤我都完成了,但仍然没有显示任何内容,我还更新了问题并添加了GetTags() 方法。
    • 哎呀!现在我得到了你:),谢谢!
    • @rapaistaliol:很高兴它有帮助。
    【解决方案2】:

    这里是你的代码:

      if(!empty($tags)){
    
        $tagShow->GetTags();
    
      }else{
        echo "There is no tag available right now!";
      }
    

    GetTags() 函数不是当前类。如果此类中的 GetTags 则使用 $this->GetTags()

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2016-04-20
      • 2020-08-24
      • 2017-07-27
      相关资源
      最近更新 更多