PHP function error Can't use function return value in write context - function returning an array. Brain slowly imploding [closed]
-
20-06-2021 - |
题
I am calling a function that returns an array, but I'm running into this error: Can't use function return value in write context
Lots of people get this error, but I can't see what I've done wrong.
This is the function:
function select_image_styles_from_category($category)
{
$image_details();
switch($category)
{
case 'twine':
$image_details[0] = get_bloginfo('template_directory') . '/images/titles/blog-twine.png';
$image_details[1] = 'on-top';
break;
case 'scrapbook':
$image_details[0] = get_bloginfo('template_directory') . '/images/blog/papers.png';
$image_details[1] = 'on-top';
break;
default:
$image_details[0] = 'stuff';
$image_details[1] = 'things';
}
return $image_details;
}
I then call this function from another function and this is the line it errors (there is more in this function, but it's just superfluous to the rest of the question):
function add_img_styles_to_special_categories($the_content_string, $category)
{
//erroring line
$image_details() = select_image_styles_from_category($category);
}
Am I missing a cast? Do I need to explicitly construct an array? Have I cocked up the case statement? I really can't see what I'm missing. Any of you gorgeous lovelies have any pointers?
解决方案
You have written code that looks like it's calling a function, when you just want to assign to a variable.
This
$image_details();
means "take the value of $image_details
, interpret it as the name of a function and call that function".
So when you (mistakenly obviously) put the extra parens and wrote
$image_details() = select_image_styles_from_category($category);
the compiler read this as "take the value of $image_details
, interpret it as the name of a function, call that function and assign the result of select_image_styles_from_category()
to it". But you cannot assign anything to the result of a function (you can only store it somewhere), hence the error.
其他提示
$image_details()
is a function call and you can't write onto a function. Do you just want to return it to the caller?
return select_image_styles_from_category($category);