tags:

views:

151

answers:

5

Hi,

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 :-(
+6  A: 
  1. With variable variables:

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

    echo $object->{'variable$WithDollar'};
    
nickf
you mean, with string variables?
Luca Matteis
No, variable variables is the correct term. But $ is illegal in variable names ...
Jan Hančič
@Jan, that doesn't change the fact that you can get a variable or a property with a $ in the name...
nickf
Oh, that seems to work ! Is there any way not to use a second variable ($myVar) ? something like : echo $object->'variable$WithDollar';)
kevin
@Kevin: I pointed out how to do that in my answer. But what are you trying to achieve in the first place? A mySQL result set with a $ in the field name is odd to say the least.
Pekka
@Pekka : It's not a MySQL result, a database adapter builds the results of a SQL query into an array of objects. The table I'm querying has a weird schema and some columns have dollar signs in their name.
kevin
@kevin: I see. Well, both nickf's, mstiles's and my approach work for that - pick your choice.
Pekka
+2  A: 

I assume you want to access properties with variable names on the fly. For that, try

echo $object->{"variable".$yourVariable}
Pekka
I'm not creating them, they are the results of an SQL query. That's not what I'm trying to do.
kevin
You can so. Try this: `$x = 'a$b'; $$x = 'foo'; print_r(get_defined_vars());`
nickf
@nickf: Good point, removed.
Pekka
+1  A: 

There are reflection methods that also allow you to construct method and attribute names that may be built by variables or contain special characters. You can use the ReflectionClass::getProperty ( string $name ) method.

$object->getProperty('variable$WithDollar');

mstiles
you'd have to use single quotes there.
nickf
+2  A: 

You don't.

The dollar sign has a special significance in PHP. Although it is possible to bypass the variable substitution in dereferencing class/object properties you NEVER should be doing this.

Don't try to declare variables with a literal '$'.

If you're having to deal with someoneelse's mess - first fix the code they wrote to remove the dollars then go and chop off their fingers.

C.

symcbean
Some of the software that primarly runs the database is 20 years old. Believe me I would love to just have readable columns names (and not AF$AT1 for example), I'm communicating with the database and can't change anything on it !
kevin
+3  A: 

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.

kevin