Donny P Donny P - 7 months ago 6
PHP Question

Syntax for accessing PHP object properties

What is the difference between accessing an object's property with

$this->$property1
compared to
$this->property1
?

When I try to use $this->$property1 I get the 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.
http://php.net/manual/en/language.oop5.properties.php

Answer
  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'
Comments