指向数组或嵌套对象的变量变量

Boo*_*orm 3 php variable-variables object-properties

是否可以创建指向数组或嵌套对象的变量变量?php文档明确指出你不能指向SuperGlobals,但它不清楚(至少对我来说)这是否适用于一般的数组.

这是我对数组var var的尝试.

     // Array Example
     $arrayTest = array('value0', 'value1');
     ${arrayVarTest} = 'arrayTest[1]';
     // This returns the correct 'value1'
     echo $arrayTest[1];
     // This returns null
     echo ${$arrayVarTest};   
Run Code Online (Sandbox Code Playgroud)

这是一些简单的代码,用于显示对象var var的含义.

     ${OBJVarVar} = 'classObj->obj'; 
     // This should return the values of $classObj->obj but it will return null  
     var_dump(${$OBJVarVar});    
Run Code Online (Sandbox Code Playgroud)

我错过了一些明显的东西吗?

joh*_*Art 5

数组元素方法:

  • 从字符串中提取数组名称并将其存储在其中$arrayName.
  • 从字符串中提取数组索引并将其存储在中$arrayIndex.
  • 正确地解析它们而不是整体.

代码:

$arrayTest  = array('value0', 'value1');
$variableArrayElement = 'arrayTest[1]';
$arrayName  = substr($variableArrayElement,0,strpos($variableArrayElement,'['));
$arrayIndex = preg_replace('/[^\d\s]/', '',$variableArrayElement);

// This returns the correct 'value1'
echo ${$arrayName}[$arrayIndex];
Run Code Online (Sandbox Code Playgroud)

对象属性方法:

  • 通过分隔符( - >)分解包含要访问的类和属性的字符串.
  • 将这两个变量分配给$class$property.
  • 分别解析它们而不是整体打开它们 var_dump()

代码:

$variableObjectProperty = "classObj->obj";
list($class,$property)  = explode("->",$variableObjectProperty);

// This now return the values of $classObj->obj
var_dump(${$class}->{$property});    
Run Code Online (Sandbox Code Playgroud)

有用!