2

Is there a way to access a member of an object, by using its name as a string?

When I declare an array...

$array = array();
$array['description_en']="hello";
$array['description_fr']="bonjour";

then I access a member like this:

$lang="en"; //just to show my purpose. it will be dynamic
$description = $array['description_'.$lang];

Can I do the same thing for objects?

For example:

$obj->description_en="hello";
$obj->description_fr="bonjour";

How can I access $obj->description_.$lang ?

3
  • 2
    $obj->{"description_".$lang} or $objRef = "description_".$lang; $obj->$objRef Commented Jul 30, 2013 at 13:01
  • @MarkBaker Can I ask why that's a comment instead of an answer? That's worth of being posted as a full answer isn't it? Commented Jul 30, 2013 at 13:03
  • 2
    @SmokeyPHP - mainly because I don't consider it worthy of answering if I can post a response in fewer characters than the limit of a tweet Commented Jul 30, 2013 at 13:05

2 Answers 2

3
class test
{
    public $description_en = 'english';
}

$obj = new test();
$lang = 'en';
echo $obj->{"description_".$lang}; // echo's "english"

You can see more examples of variable variables here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you ! and all the other answers.
2

You can use this syntax:

<?php

class MyClass {
    public $varA = 11;
    public $varB = 22;
    public $varC = 33;
}

$myObj = new MyClass();

echo $myObj->{"varA"} . "<br>";
echo $myObj->{"varB"} . "<br>";
echo $myObj->{"varC"} . "<br>";

This way, you can access object variables as if they were entries in an associative array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.