Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a PHP object attribute having a dollar sign?

Tags:

oop

php

I have a PHP Object with an attribute having a dollar ($) sign in it.

How do I access the content of this attribute ?

Example :

echo $object->variable; // Ok

echo $object->variable$WithDollar; // Syntax error :-(
like image 849
kevin Avatar asked Jan 19 '10 11:01

kevin


People also ask

What does dollar sign mean in PHP?

$ is the way to refer to variables in PHP. Variables in PHP are dynamically typed, which means that their type is determined by what's assigned to them. Here's the page about variables from the PHP manual. $a = "This is a string"; $b = 1; // This is an int.

How Can Get object property value in PHP?

The get_object_vars() function is an inbuilt function in PHP that is used to get the properties of the given object. When an object is made, it has some properties. An associative array of properties of the mentioned object is returned by the function. But if there is no property of the object, then it returns NULL.

Why do we use a dollar symbol ($) before variables in PHP?

What does $$ (dollar dollar or double dollar) means in PHP ? The $x (single dollar) is the normal variable with the name x that stores any value like string, integer, float, etc. The $$x (double dollar) is a reference variable that stores the value which can be accessed by using the $ symbol before the $x value.

What is the use of sign in PHP?

It makes PHP suppress any error messages (notice, warning, fatal, etc) generated by the associated expression. It works just like a unary operator, for example, it has a precedence and associativity.


2 Answers

  1. With variable variables:

    $myVar = 'variable$WithDollar';
    echo $object->$myVar;
    
  2. With curly brackets:

    echo $object->{'variable$WithDollar'};
    
like image 179
nickf Avatar answered Oct 13 '22 00:10

nickf


Thanks to your answers, I just found out how I can do that the way I intended :

echo $object->{'variable$WithDollar'}; // works !

I was pretty sure I tried every combination possible before.

like image 27
kevin Avatar answered Oct 13 '22 01:10

kevin