In the following script I try to set the values for $var_1 and $var_2 using the set method for the object $obj. But when I call the get method to retrieve the values set for that object,I get a blank. Why is that ?
<?php
class Tester {
public $var_1;
public $var_2;
public function set() {
$var_1 = 20;
$var_2 = "Tu jo aa jaaye..toh is ghar ko sawanrta dekhun";
}
public function get() {
return "Var_1 is : {$var_1} and Var_2 is : {$var_2}";
}
}
$obj = new Tester();
$obj_c = clone $obj;
$obj_nc = $obj;
$obj->set();
echo $obj->get();
echo $obj_nc->get();
The
$thisis required in PHP. You’re referencing local variables otherwise.As a side note, you should develop with
display_errorsOnanderror_reportingcranked all the way up. If that had been the case, you would have seen notices that you were references undefined variables. (Note that error_reporting arguably should be cranked all the way up on production servers [if your code was coded with it mind], butdisplay_errorsshould never beOnin a production environment — logs should be used instead.)