我想访问并为私有静态类属性赋值,我想使用'变量变量'的概念进行赋值。访问作品,但分配不起作用。我尝试过以下方法:
class AClass {
private static $testArray = array();
public static function aFunction() {
$key = 'something';
$arrayName = 'testArray';
$array = self::$$arrayName;
// accessing:
$value = $array[$key]; // This works, $value holds what self::testArray['something'] holds.
// assigning:
// version 1:
$array[$key] = $value; // No error, but self::testArray['something'] does not get updated
// version 2:
self::$$arrayName[$key] = $value; // Error
}
}
另外:我在提出一个精确而简洁的标题时遇到了一些麻烦。如果你觉得你理解我的问题,并且可以想到一个更好的头衔,请求建议吧!
答案 0 :(得分:2)
对于版本1,
您的数组可能是静态数组的副本,因此赋值只能在本地副本上进行。 从PHP 5开始,默认情况下,对象通过引用传递,但我认为数组仍然可以通过副本传递(除非你特别引用了&) - 不是100%肯定这一点
对于版本2,
您应该尝试self::${$arrayName}[$key]
存在优先级顺序问题,您希望PHP在解释[]之前评估您的“var's var”。没有{}
,PHP正在尝试评估类似
self::${$arrayName[$key]}
而不是
self::${$arrayName}[$key]
答案 1 :(得分:1)
<?php
class AClass {
private static $testArray = array('something'=>'check');
public static function aFunction() {
$key = 'something';
$arrayName = 'testArray';
$array = self::$$arrayName;
// accessing:
$value = $array[$key]; // This works, $value holds what self::testArray['something'] holds.
// assigning:
// version 1:
$array['something'] = 'now'; // No error, but self::testArray['something'] does not get updated
//updated value;
// need to assgig the value again to get it updated ......
/*
**if $a = '10';
$b = $a;
$b = 20 ; // will it update $a ..?? ANSWER is NO
same logic applies here**
if you use $b = &$a ; then case is different
*/
self::$$arrayName = $array;
print_r( self::$$arrayName);
// version 2:
// since you are using the key also you have to keep arrayName seperate "note {}"
self::${$arrayName}[$key] = $value;
print_r( self::$$arrayName);
}
}
$obj = new AClass();
$obj->aFunction();
?>