Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 526
Don P Avatar asked Sep 24 '12 18:09

Don P


People also ask

How do you access the properties of an object in PHP?

The most practical approach is simply to cast the object you are interested in back into an array, which will allow you to access the properties: $a = array('123' => '123', '123foo' => '123foo'); $o = (object)$a; $a = (array)$o; echo $o->{'123'}; // error!

What is PHP object syntax?

In PHP, Object is a compound data type (along with arrays). Values of more than one types can be stored together in a single variable. Object is an instance of either a built-in or user defined class. In addition to properties, class defines functionality associated with data.

How can we access properties and methods of a class in PHP?

Once you have an object, you can use the -> notation to access methods and properties of the object: $object -> propertyname $object -> methodname ([ arg, ... ] ) Methods are functions, so they can take arguments and return a value: $clan = $rasmus->family('extended');


1 Answers

  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' 
like image 131
Sposmen Avatar answered Oct 01 '22 00:10

Sposmen