Why it uses the Constructor?

class 1:

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

class 2:

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.

That would not work as you are not sending in an argument.

Change class 2 slightly to this;


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


Then doing :


$obj=new HelloWorld;
echo $obj->getHtml();

will at least spit out a default value, if not it is up to you to check for a missing argument.

Because when you create an instance of your “HelloWorld” object, you can initialize values upon creation making your object more flexible, e.g. using class2 $obj1 = new HelloWorld(“john”);, $obj2 = new HelloWorld(“doe”).

If you look at this the way you can create an object (see the last line).

class Test 
{

	private $_data;

	public function __construct($string)
	{
		// Set the Test class $_data variable to whatever they input
		$this->_data = $string;
	}
	
	public function PrintIt()
	{
		print $this->_data;
	}
}

$item = new Test('Hey I am calling this when we create the object');

you should check out Lynda.com for PHP beyond the basics it’ll give you a detail insight on Class files

You can instantiate (create an object inside a method of the second class), sure.

in class 2,could i make an object like this, $obj=new HelloWorld; ?