如何更正此非法字符串偏移量? [英] How do I correct this Illegal String Offset?
问题描述
我在第 32 行收到此错误警告:非法字符串偏移量‘类型’在/home/mysite/public_html/wp-content/themes/evento/lib/php/extra.class.php"
I am receiving this error "Warning: Illegal string offset 'type' in /home/mysite/public_html/wp-content/themes/evento/lib/php/extra.class.php on line 32"
并且我意识到文件中的这部分代码是错误的,但是我在 PHP 方面还不是很好,我想知道是否有人可以帮助我重新编写这部分以消除错误.谢谢!(错误从第 32 行开始,这是下面 if 语句的开头)
and I realized this section of code in the file is wrong, however I'm not that great in PHP yet and I am wondering if someone can help me re-write this section to eliminate the error. Thanks! (the error starts on line 32 which is the beginning of the if statement below)
代码如下:
/* new version */
function get_attachment_struct( $inputs ){
$attach = array();
if( $inputs['type'] == 'attach' ){
$name = $inputs['name'];
$attach = array(
0 => array(
'name' => $name,
'type' => 'text',
'label' => 'Attachment URL',
'lvisible' => false,
'upload' => true,
),
1 => array(
'name' => $name .'_id',
'type' => 'hidden',
'upload' => true
),
);
if( isset( $inputs[ 'classes' ] ) ){
$attach[0]['classes'] = $inputs[ 'classes' ];
$attach[1]['classes'] = $inputs[ 'classes' ] . '_id';
}
}
return $attach;
}
/* new version */
推荐答案
if ($inputs['type'] == 'attach') {
代码是有效的,但它要求函数参数 $inputs
是一个数组.使用 $inputs['type']
时的非法字符串偏移"警告意味着该函数正在传递一个字符串而不是数组.(然后由于字符串偏移量是一个数字,'type'
不合适.)
The code is valid, but it expects the function parameter $inputs
to be an array. The "Illegal string offset" warning when using $inputs['type']
means that the function is being passed a string instead of an array. (And then since a string offset is a number, 'type'
is not suitable.)
所以理论上问题出在其他地方,代码的调用者没有提供正确的参数.
So in theory the problem lies elsewhere, with the caller of the code not providing a correct parameter.
但是,此警告消息是 PHP 5.4 的新增内容.如果发生这种情况,旧版本没有警告.他们会默默地将 'type'
转换为 0
,然后尝试获取字符串的字符 0(第一个字符).因此,如果这段代码应该可以工作,那是因为滥用这样的字符串不会导致对 PHP 5.3 及以下版本的任何抱怨.(很多老PHP代码升级后都遇到过这个问题.)
However, this warning message is new to PHP 5.4. Old versions didn't warn if this happened. They would silently convert 'type'
to 0
, then try to get character 0 (the first character) of the string. So if this code was supposed to work, that's because abusing a string like this didn't cause any complaints on PHP 5.3 and below. (A lot of old PHP code has experienced this problem after upgrading.)
您可能希望通过检查调用代码来调试为什么函数被赋予一个字符串,并通过执行 var_dump($inputs); 来找出它的值代码>在函数中.但是,如果您只是想关闭警告以使其表现得像 PHP 5.3,请将行更改为:
You might want to debug why the function is being given a string by examining the calling code, and find out what value it has by doing a var_dump($inputs);
in the function. But if you just want to shut the warning up to make it behave like PHP 5.3, change the line to:
if (is_array($inputs) && $inputs['type'] == 'attach') {
这篇关于如何更正此非法字符串偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!