Learning php Classes, stuck on __contruct();

2019-08-23 05:40发布

So I'm trying to learn phpOOP after stopping programming for a few years, so I'm a bit rusty.

Anyway, I have a class blogEntry so I can display blog entries that have been cleaned with the function cleanForDisplay by echo'ing $blogEntry->article for example. But I am receiving no errors, and the variable is not being displayed.

Thanks

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

标签: php oop
2条回答
对你真心纯属浪费
2楼-- · 2019-08-23 06:35

You have a typo, the magic method is __construct() and you are not receiving any error because the constructor is not mandatory in PHP.

Also, the $row variable is not defined, so you fields will be null even with the constructor.

查看更多
Luminary・发光体
3楼-- · 2019-08-23 06:36

Your method is spelt incorrectly. It should read __construct().

Secondly, you are not passing in any parameters to the method, and thus, $row is undefined.

Consider the following:

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 is passed in as the parameter, and therefore, the variables you are trying to set will be defined.

The blogEntry class can be initialized as follows:

$blogEntry = new blogEntry($rowFromDB);
查看更多
登录 后发表回答