简体   繁体   中英

Get value of item from array class property dynamically in PHP

I have an object named Model like this:

class Model {
    public $menu;
}

In a function I instantiate a new Model like this:

public function Hello(){
    $model = new Model();
    $model->menu['home'] = 'Hi there';
}


In my plan I have a Model class that can contain several properties. These properties I want to be able to get them in my view (html file). There are <!-- $model.{PropertyName} --> elements that are replaced by the property value that is available in the Model class. In this specific scenario I have a property $menu that is an array like displayed above.


Now, I have some piece of code that extracts a string value where the result of this string is menu['home'] . With this string I try to read the model it's property menu .

So:

 private function Action($model){ $foo = "menu['home']"; //Get value of $foo $value = $model->$foo; } 

I expect to get 'Hi there' but instead I get an Notice : Notice: Undefined property: Model::$menu['home'] in ....script.php on line X

When I directly access the property it works!

Any idea how I can get the array item it's value?

Your $model instance doesn't have a member with the name menu['home'] so you can't really access it this way. You have several options here:

option 1 - split the string and use two variables:

$foo = "menu";
$bar = "home";

//Get value of $foo[$bar]
$value = $model->{$foo}[$bar];

You can also split it using php code if you don't the values in two different variables.

option 2 - use eval (which i really recommend against!)

$foo = "menu['home']";

//Get value of $foo

die('ARE YOU SURE YOU REALLY WANT THIS?!?!?!');

$value = eval('return $model->'.$foo.';');
var_dump($value);

Note that using eval when not required is really not a good practice!!! and makes your code vulnerable .

To solve this, you need a PHP-Mechanism which is called "variable variables" (see http://php.net/manual/en/language.variables.variable.php ) for more Information.

In your case, you can access your variable by: $value = $model->${$foo};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM