关联数组$ myArray的var_dump如下所示:
array (size=522) 0 => array (size=3) 'id' => int 1 'url' => string 'introduction' (length=12) 'title' => string 'Introduction' (length=12) 1 => array (size=3) 'id' => int 2 'url' => string 'first_steps' (length=11) 'title' => string 'First steps' (length=11) 2 => ...当我将关联数组中的元素值赋给函数时,为了执行一些字符串操作,我得到一个错误:
“可捕获的致命错误:传递给doStringManipulation()的参数1必须是字符串的实例,给定的字符串......”
字符串操作在foreach循环中调用:
foreach($myArray as $row){ ... $s = doStringManipulation((string) $row['url']); // triggers error ... } function doStringManipulation(string str){ ... return $result; // string }不管我是否将$ row ['url']转换为字符串都没有什么区别。 即使var_dump确认元素值是一个字符串,我总会得到错误。
我在这里错过了什么?
谢谢!
The var_dump of the associative array $myArray is as follows:
array (size=522) 0 => array (size=3) 'id' => int 1 'url' => string 'introduction' (length=12) 'title' => string 'Introduction' (length=12) 1 => array (size=3) 'id' => int 2 'url' => string 'first_steps' (length=11) 'title' => string 'First steps' (length=11) 2 => ...When I assign the values of elements in the associative array to a function, to perform some string manipulation, I get an error:
"Catchable fatal error: Argument 1 passed to doStringManipulation() must be an instance of string, string given, ..."
The string manipulation is called inside a foreach loop:
foreach($myArray as $row){ ... $s = doStringManipulation((string) $row['url']); // triggers error ... } function doStringManipulation(string str){ ... return $result; // string }Whether or not I cast $row['url'] to string doesn't make a difference. I always get the error, even though var_dump confirms that the element value is a string.
What am I missing here?
Thanks!
最满意答案
我会假设你没有使用PHP 7。
错误指出它需要一个字符串实例(哪个php没有),这是因为你在function doStringManipulation(string str){中键入提示string 。 类型提示不适用于数组和对象。
我的建议:
function doStringManipulation($str) { // assuming 'str' was a typo here if ( ! is_string($str)) { return ''; } ... return $result; // string }欲了解更多信息,请参阅: http : //php.net/manual/en/migration70.new-features.php
I'm going to assume you're not using php 7.
The error states that it requires an instance of string (which php does not have), this is because you are type hinting string in function doStringManipulation(string str){. Type hinting does not work on anything but on arrays and objects.
My suggestion:
function doStringManipulation($str) { // assuming 'str' was a typo here if ( ! is_string($str)) { return ''; } ... return $result; // string }For more info see: http://php.net/manual/en/migration70.new-features.php
更多推荐
发布评论