指向数组或嵌套对象的变量 [英] Variable Variables Pointing to Arrays or Nested Objects

查看:84
本文介绍了指向数组或嵌套对象的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建指向数组或嵌套对象的变量变量? php文档专门说您不能指向SuperGlobals,但不清楚(至少对我而言),这是否适用于一般数组.

Is it possible to create a variable variable pointing to an array or to nested objects? The php docs specifically say you cannot point to SuperGlobals but its unclear (to me at least) if this applies to arrays in general.

这是我尝试使用数组var var的尝试.

Here is my try at the array var var.

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

这里有一些简单的代码来说明对象var var的含义.

Here is some simple code to show what I mean by object var var.

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

我在这里缺少明显的东西吗?

Am I missing something obvious here?

推荐答案

数组元素方法:

  • 从字符串中提取数组名称,并将其存储在$arrayName中.
  • 从字符串中提取数组索引,并将其存储在$arrayIndex中.
  • 正确解析它们,而不是整体解析.
  • Extract array name from the string and store it in $arrayName.
  • Extract array index from the string and store it in $arrayIndex.
  • Parse them correctly instead of as a whole.

代码:

$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];

对象属性方法:

  • 使用分隔符(->)展开包含要访问的类和属性的字符串.
  • 将这两个变量分配给$class$property.
  • 分别解析它们,而不是整体解析var_dump()
  • Explode the string containing the class and property you want to access by its delimiter (->).
  • Assign those two variables to $class and $property.
  • Parse them separately instead of as a whole on var_dump()

代码:

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

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

有效!

这篇关于指向数组或嵌套对象的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆