March 14, 2012

variable key name

Question by thelolcat

Can I check for a variable key without using a temporary variable.

$var = 'blabla';
$key = "{$var}_abc";

if(isset($someobject->$key))...

?

with arrays you can do this… $array[“{$var}_abc”]

Answer by salathe

Yes. You can use curly braces containing an expression resulting in a string, where that string is the name of the property you want to check.

$someobject->{"{$var}_abc"}
$someobject->{$var."_abc"}

Answer by Starx

You can do this, using property_exists() method

if(property_exists($object, $var."_abc")) {
 // do stuff
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!