Why declare constructor


<?php
class books {
//public
public $title = array();
public $image = array();
public $author = array();
public $description = array();
public $year = array ();
public $price = array();
// private
private $filename = "data.txt";
//class constructor
function __construct()
{

$i=-1;
$lines = file($this->filename);
foreach ( $lines as $line) {
if (strlen($line) > 2) {
$line = rtrim($line);
list($what, $content) = explode("=> ", $line);
if ($what == "Title") {
$i++;
$this->title[$i]=$content;
}
elseif ($what == "Image") {
$this->image[$i]=$content;
}
elseif ($what == "Author") {
$this->author[$i]=$content;
}
elseif ($what == "Description") {
$this->description[$i]=$content;
}
elseif ($what == "Year") {
$this->year[$i]=$content;
}
elseif ($what == "Price") {
$this->price[$i]=$content;
};
};
};
} // end constructor
} // end GetData


as i know,in class, i can declare function optionally.but why i shoud declare a function like this"function __constructor(){ }".don’t know when i should declare constructors in a class and what’s the role it plays in a class. thank you.

http://nl3.php.net/manual/en/function.file.php

:cool:

got it,thank you,.what’s this line meaning “$lines = file($this->filename);” ?

The __construct() function is run when an object is created (constructed). You can use it to run code that has to be run when the object is created (such as retrieving data from a database or loading other objects etc.).