What is the syntax for accessing PHP object properties? [closed]

感情迁移 提交于 2019-11-27 16:01:09
Sposmen
  1. $property1 // specific variable
  2. $this->property1 // specific attribute

The general use on classes is without "$" otherwise you are calling a variable called $property1 that could take any value.

Example:

class X {
  public $property1 = 'Value 1';
  public $property2 = 'Value 2';
}
$property1 = 'property2';  //Name of attribute 2
$x_object = new X();
echo $x_object->property1; //Return 'Value 1'
echo $x_object->$property1; //Return 'Value 2'

$this->property1 means:

use the object and get the variable property1 bound to this object

$this->$property1 means:

evaluate the string $property1 and use the result to get the variable named by $property1 result bound to this object

property1 is a string while $property1 is a variable. So when accessing $this->$property1 PHP looks for contents of the variable named $property1 and because it (probably) doesn't exist it's empty so that's why you get the Cannot access empty property error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!