Page 1 of 1

why it uses the Constructor?

Posted: Sat Aug 14, 2010 3:30 am
by everydayrun
class 1:

Code: Select all

class HelloWorld 
{ public $world; 
function getHtml() 
{ return "<html><body>". "Hello, ".$this->world."!". "</body></html>"; } }
 
class 2:

Code: Select all

class HelloWorld {
public $world;
function __construct($world) {
$this->world = $world;
}
function getHtml() {
return "<html><body>".
"Hello ".$this->world."!".
"</body></html>";
}
}
i don't know why in class 2 it uses a construct function. i feel it is unnecessary .any tips would be appreciated.

Re: why it uses the Constructor?

Posted: Sat Aug 14, 2010 5:16 am
by MindOverBody
In class one, $world variable should be predefined inside class. But in class two, when making object of a class, $world parameter should be given.

Constructor is function which is triggered upon making instance of class.

For example, class two:

Code: Select all

// constructor is registering $world variable with "Earth" string
$hw = new HelloWorld("Earth");
echo $hw -> getHtml();
will print on screen:

Code: Select all

Hello Earth