What is the difference between Php $ this & # 8594; $ propery_name and $ this-> propery_name
$protected_property_name = '_'.$name;
if(property_exists($this, $protected_property_name)){
return $this->$protected_property_name;
}
I am following an Object Oriented Programming tutorial, however, the instructor came up with a new code structure that I have not seen before, without clearly explaining why he did it. if you notice in the if () statement $ this -> $ protected_property_name has two $ signs, one for $ this and the other for $ protected_property_name should usually be $ this-> protected_property_name without a dollar sign in the protected_property_name variable. when I tried to remove the $ sign from the protected_property_name variable an error was thrown. the complete code looks like this
class Addrress{
protected $_postal_code;
function __get($name){
if(!$this->_postal_code){
$this->_postal_code = $this->_postal_code_guess();
}
//Attempt to return protected property by name
$protected_property_name = '_'.$name;
if(property_exists($this, $protected_property_name)){
return $this->$protected_property_name;
}
//Unable to access property; trigger error.
trigger_error('Undefined property via __get:() '. $name);
return NULL;
}
}
+3
source to share
2 answers
This is an example class:
class Example {
public $property_one = 1;
public $property_two = 2;
}
You can see the difference in the following codes:
$example = new Example();
echo $example->property_one; //echo 1
$other_property = 'property_two';
echo $example->$other_property; // equal to $example->property_two and echo 2
Non-OOP example:
$variable_one = 100;
$variable_name = 'variable_one';
echo $$variable_name; // equal to echo $variable_one and echo 100
+2
source to share