学习php类,停留在__contract();上;


Learning php Classes, stuck on __contruct();

所以在停止编程几年后,我正在尝试学习phpOOP,所以我有点生疏。

无论如何,我有一个类blogEntry,这样我就可以显示已经用cleanForDisplay函数清理过的博客条目,例如通过echo'ing$blogEntry->文章。但我没有收到任何错误,变量也没有显示。

感谢

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'];
  }
}

您有一个拼写错误,神奇的方法是__construct(),并且您没有收到任何错误,因为构造函数在PHP中不是强制性的。

此外,$row变量没有定义,因此即使使用构造函数,字段也将为null。

您的方法拼写错误。它应该读__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);