[英]PHP - Array fatal error
I've got an odd error in my PHP code regarding dynamic arrays. 我的PHP代码中有一个关于动态数组的奇怪错误。
The error outputted is: 输出的错误是:
Fatal error: Cannot use string offset as an array ... on line 89
This is a portion of my code, it is within a foreach loop, which is looping through settings in a database: 这是我的代码的一部分,它在foreach循环中,该循环遍历数据库中的设置:
foreach($query->fetchAll() as $row)
{
if($site!=CURRENT_SITE_TEMPLATE)
{
$property = 'foreignSettings';
$propertyType = 'foreignSettingsTypes';
} else {
$property = 'settings';
$propertyType = 'settingTypes';
}
$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
settype($this->$property[$row['variable_section']][$row['variable_name']],$row['variable_type']);
$this->$propertyType[$row['variable_section']][$row['variable_name']] = $row['variable_type'];
}
For the sake of the example code, $site
is 'admin' and CURRENT_SITE_TEMPLATE
is 'admin'. 对于示例代码,
$site
为“ admin”, CURRENT_SITE_TEMPLATE
为“ admin”。 In addition, $foreignSettings, $foreignSettingsTypes, $settings, and $settingTypes
are all defined as arrays in the class scope 此外,
$foreignSettings, $foreignSettingsTypes, $settings, and $settingTypes
均在类范围内定义为数组。
The error is on line 89, which is: 该错误在第89行上,它是:
$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
I originally thought it was because of the $property variable accesing the array, however, this looks like valid legal code in the PHP documentation ( http://php.net/manual/en/language.variables.variable.php in example #1
) 我最初以为是因为$ property变量访问数组,但是,这看起来像PHP文档中的有效法律代码(
example #1
http://php.net/manual/zh/language.variables.variable.php 。 example #1
)
Any help on this error would be appreciated. 对此错误的任何帮助将不胜感激。
Thanks 谢谢
In your given example $property
is a string. 在您给出的示例中,
$property
是一个字符串。 You are then trying to use that as an array. 然后,您尝试将其用作数组。 Strings only has numeric indexes (if you need to use as an array).
字符串仅具有数字索引(如果需要用作数组)。
The problem is as follows: $this->$property[0]
means you access the 0th place of $property which in your case would be the first letter of the string $property. 问题如下:
$this->$property[0]
表示您访问$ property的第0位,在您的情况下,它将是字符串$ property的第一个字母。 Thus you end up with $this->f or $this->s. 因此,您最终得到$ this-> f或$ this-> s。
with $this->$property[0][0]
you would be trying to access the 0th place of the 0th place of the $property string what results in an error because you try to access the 0th place of the char s what is not possible since the char s can not be referenced as an array. 使用
$this->$property[0][0]
您将尝试访问$ property字符串的第0位的第0位,这将导致错误,因为您尝试访问char的第0位是什么。由于char不能作为数组引用,因此不可能。
what you want is $this->{$propperty}[0][0]
what means that you try to access the 0th place of the 0th place of the variable that has the name $propperty. 您想要的是
$this->{$propperty}[0][0]
这意味着您尝试访问名称为$ propperty的变量的第0位的第0位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.