开发者

How to create a multiple dyanmic object reference in PHP?

开发者 https://www.devze.com 2023-03-16 03:48 出处:网络
I have a string with \'item->anotheritem\' I want to use this as a dyanmic variable. Is this possible?

I have a string with 'item->anotheritem'

I want to use this as a dyanmic variable. Is this possible? e.g:

$string = 'item->anotheritem';
$obj->$string;

Ultimately trying to end up with the following, but it doesn't seem to like it. Any i开发者_高级运维deas?:

$object->item->anotheritem;

Using PHP Version 5.3.2


In the first block of code, are you trying to parse the variable name as a string to the variable $string? It doesn't match what you are trying to doing in the second code.


There are two ways to do this. First, you can manually break up the string and evaluate each element on the object, or second you can use PHP's eval() function. I don't recommend the latter, though since it is very scary from a security standpoint. Here is what those two mechanisms look like:

<?php
// Get some test data...
$obj = new stdClass;
$obj->item = new stdClass;
$obj->item->anotheritem = "Goal!";
$string = 'item->anotheritem';

// Method #1
$target = $obj;
$parts = explode('->', $string);
foreach ($parts as $part) {
    $target = $target->{$part};
}
var_dump($target);

// Method #2 -- Avoid like the plague! ;)
$target2 = eval('return $obj->item->anotheritem;');
var_dump($target2);
0

精彩评论

暂无评论...
验证码 换一张
取 消