why it uses the Constructor?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
everydayrun
Forum Commoner
Posts: 51
Joined: Wed Jan 20, 2010 1:30 am

why it uses the Constructor?

Post 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.
User avatar
MindOverBody
Forum Commoner
Posts: 96
Joined: Fri Aug 06, 2010 9:01 pm
Location: Osijek, Croatia

Re: why it uses the Constructor?

Post 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
Post Reply