【问题标题】:Learning php Classes, stuck on __contruct();学习php类,卡在__construct();
【发布时间】:2013-07-22 21:40:21
【问题描述】:

所以我停了几年编程,想学phpOOP,所以有点生疏了。

无论如何,我有一个 blogEntry 类,因此我可以通过例如回显 $blogEntry->article 来显示已使用函数 cleanForDisplay 清理的博客条目。但我没有收到任何错误,也没有显示变量。

谢谢

class blogEntry
 {
  var $headline;
  var $author;
  var $date;
  var $image;
  var $imagecaption;
  var $article;

  public function __contruct()
  {
    $this->headline = cleanForDisplay($row['headline']);
    $this->author = cleanForDisplay($row['postedby']);
    $this->imagecaption = cleanForDisplay($row['imagecaption']);
    $this->article = cleanForDisplay($row['article']);
    $this->image = $row['image'];
    $this->date = $row['date'];
  }
}

【问题讨论】:

  • 在您的构造函数中,您从哪里获取 $row['headline']、$row['postedby'] 等的值?另外,你是如何访问这个类的?
  • 你从哪里得到$row?通常,您应该将一个 ID 传递给构造函数,然后使用准备好的语句在数据库中查找该项目。 contruct !== construct.
  • 还有,cleanForDisplay是blogEntry类的一个函数吗?
  • ^^ 如果不是,它应该是另一个类的一部分,真正的 OOP。
  • 当您说“变量未显示”时,您在哪里将其回显到屏幕上? (在另一个函数中?)。我会做一个 var_dump($instance->article);查看变量是否已设置。

标签: php oop


【解决方案1】:

你有一个错字,魔术方法是__construct(),你没有收到任何错误,因为构造函数在 PHP 中不是强制性的。

此外,$row 变量未定义,因此即使使用构造函数,您的字段也会为空。

【讨论】:

    【解决方案2】:

    您的方法拼写错误。它应该是__construct()

    其次,您没有向方法传递任何参数,因此,$row 未定义。

    考虑以下几点:

    public function __construct($row)
    {
     $this->headline = cleanForDisplay($row['headline']);
     $this->author = cleanForDisplay($row['postedby']);
     $this->imagecaption = cleanForDisplay($row['imagecaption']);
     $this->article = cleanForDisplay($row['article']);
     $this->image = $row['image'];
     $this->date = $row['date'];
    }
    

    $row 作为参数传入,因此将定义您尝试设置的变量。

    blogEntry类可以如下初始化:

    $blogEntry = new blogEntry($rowFromDB);
    

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2019-10-27
      • 1970-01-01
      • 2015-06-21
      相关资源
      最近更新 更多