PHP function error Can't use function return value in write context - function returning an array. Brain slowly imploding [closed]

StackOverflow https://stackoverflow.com/questions/11468071

Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

$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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top