Reputation: 3
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!
Upvotes: 0
Views: 118
Reputation: 5973
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
Upvotes: 1
Reputation: 10185
You use php version 5.0-5.6. you cant specify string as function argument. Code must looks like
/**
* @var String str
*/
function doStringManipulation(str){
...
return $result; // string
}
Or update php up to 7
Upvotes: 0