Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Php $this->$propery_name and $this->propery_name

Tags:

php

    $protected_property_name = '_'.$name;
    if(property_exists($this, $protected_property_name)){
        return $this->$protected_property_name;
    }

I am following a tutorial on object-oriented programming, however, the instructor came up with a new code structure that I have not seen before without a clear explanation of why he did so. if you notice within the if(statement) the $this->$protected_property_name statement has two $ signs one for the $this and the other for the $protected_property_name normally it should only be $this->protected_property_name without having a dollar sign on the protected_property_name variable. when I tried to remove the $ sign from the protected_property_name variable an error was triggered. 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;        
}
}
like image 541
Salim Avatar asked Nov 30 '25 11:11

Salim


1 Answers

Let us assume that we have a class

class Test {
   public $myAttr = 1;
}
var $x = new Test();

We can access the public attribute like $x->myAttr.

What if we have the name of the attribute in a variable, like

$var = 'myAttr';

We can access the value of the attribute with $x->$var

like image 144
Alexios Tsiaparas Avatar answered Dec 03 '25 06:12

Alexios Tsiaparas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!