【发布时间】:2018-02-23 20:11:37
【问题描述】:
上下文: 在安装了我的 WordPress 插件的一个站点上,我看到了一系列 PHP 警告,但我不完全确定为什么会发生这种情况。我希望这里有人可以帮助我弄清楚如何解决这个警告。
代码示例:
function my_function( $array ) {
if ( ! isset( $array['where'] ) ) { $array['where'] = 'after'; }
if ( ! isset( $array['echo'] ) ) { $array['echo'] = false; }
if ( ! isset( $array['content'] ) ) { $array['content'] = false; }
$array['shortcode'] = true;
$array['devs'] = true;
return social_warfare( $array );
}
add_shortcode( 'my_shortcode', 'my_function' );
警告:
警告:非法字符串偏移 'where' in /home/playitda/public_html/domain.com/wp-content/plugins/my_plugin/functions/frontend-output/shortcodes.php 第 14 行
警告:非法字符串偏移 'echo' in /home/playitda/public_html/domain.com/wp-content/plugins/my_plugin/functions/frontend-output/shortcodes.php 在第 15 行
警告:不能将空字符串分配给字符串偏移量 /home/playitda/public_html/domain.com/wp-content/plugins/my_plugin/functions/frontend-output/shortcodes.php 在第 15 行
警告:非法字符串偏移“内容”在 /home/playitda/public_html/domain.com/wp-content/plugins/my_plugin/functions/frontend-output/shortcodes.php 第 16 行
警告:不能将空字符串分配给字符串偏移量 /home/playitda/public_html/domain.com/wp-content/plugins/my_plugin/functions/frontend-output/shortcodes.php 第 16 行
警告:非法字符串偏移“短代码”在 /home/playitda/public_html/domain.com/wp-content/plugins/my_plugin/functions/frontend-output/shortcodes.php 第 18 行
警告:非法字符串偏移 'devs' in /home/playitda/public_html/domain.com/wp-content/plugins/my_plugin/functions/frontend-output/shortcodes.php 第 19 行
由于某种原因,它每次遇到数组中的一个索引时都会发出警告。我该如何解决?谢谢!
【问题讨论】:
-
看起来函数需要一个数组,而是得到一个字符串。
-
那么我怎样才能强制它成为一个数组呢?我是在参数中声明它还是在继续之前检查它并使其成为一个数组?
-
是的,您可以在函数签名中使用'type hint'(远远超过现在使用 7.+ 的提示)或显式检查类型...
is_array。修复虽然是在期望数组时不传递字符串。 -
我喜欢 is_array 检查,因为这样,如果某些 lughead 将非数组传递给它,我可以简单地取消设置它,然后使用我的默认数组值代替它而不会引发错误。
-
if ( ! is_array ( $array ) ) $array = [];在函数开头将确保您有一个数组