PHP OOP, Uncaught Error: Call to a member function setAuthor() on string

PHP OOP, Uncaught Error: Call to a member function setAuthor() on string

我使用 PHP 版本 7,但在创建新闻文章时总是出现此错误:

Fatal error: Uncaught Error: Call to a member function setAuthor() on string in D:\xampp\htdocs\entwicklung\tools\adminlogin\lib\mod\news\newsForm.php:14 Stack trace: #0 {main} thrown in D:\xampp\htdocs\entwicklung\tools\adminlogin\lib\mod\news\newsForm.php on line 14

在这里我创建了我的对象并将文章保存在我的数据库中:

if(isset($_POST["publish"]))
{
    $news = new News();
    $title = $news->setTitle($db, $_POST["ueberschrift"]);
    $news =  $news->setNews($db, $_POST["artikel"]);
    $author = $news->setAuthor($db, $_POST["autor"]); //This is line 14

    News::newsArticleCreate($db, $title, $news, $author);

}

这是我给作者的setter-方法:

    function setAuthor($db, $author)
    {
        if(!empty($author))
        {
            $author = mysqli_real_escape_string($db, $author);
            return $this->author = trim($author);
        }
        else
        {
            return false;
        }
    }

我的错误是什么?

Fatal error: Uncaught Error: Call to a member function setAuthor() on string

错误表明您正在尝试对字符串 ( $news ) 而不是 News Class 的对象调用 setAuthor。 如果您替换以下行:

$news =  $news->setNews($db, $_POST["artikel"]);

$news->setNews($db, $_POST["artikel"]);

它应该可以正常工作。