Don P
Don P

Reputation: 63537

How to access a class object property? $this->$property1 gives a "Cannot access empty property" error

How do you access a PHP object's properties?

Also, what is the difference between accessing an object's property with $this->$property1 vs. $this->property1?

When I try to use $this->$property1 I get the following error:

'PHP: Cannot access empty property'.

PHP's documentation on object properties has one comment which mentions this, but the comment doesn't really explain in depth.

Upvotes: 35

Views: 68958

Answers (3)

Sposmen
Sposmen

Reputation: 731

  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'

Upvotes: 41

Miha Rekar
Miha Rekar

Reputation: 1546

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.

Upvotes: 3

JvdBerg
JvdBerg

Reputation: 21856

$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

Upvotes: 18

Related Questions