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
everydayrun
Forum Commoner
Posts: 51 Joined: Wed Jan 20, 2010 1:30 am
Post
by everydayrun » Sat Aug 14, 2010 3:30 am
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.
MindOverBody
Forum Commoner
Posts: 96 Joined: Fri Aug 06, 2010 9:01 pm
Location: Osijek, Croatia
Post
by MindOverBody » Sat Aug 14, 2010 5:16 am
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: