2

I am currently learning the basics of MVC. I am running into a php fatal error with the code below. The error states Can't use method return value in write context. How can I fix this?

    $module = empty( $uri->fragment(0) ) ? 'index' : $uri->fragment(0);

2 Answers 2

1

This is because empty() is a language construct and until recently it only allowed variable references as its argument, whereas your code passes a return value (which is not a reference).

Fortunately, because a return value wouldn't be undefined or non-existent, you can use a shortened ternary operator:

$module = $uri->fragment(0) ?: 'index';

Before 5.3 you would have to use the longer version:

$module = $uri->fragment(0) ? $uri->fragment(0) : 'index';
Sign up to request clarification or add additional context in comments.

Comments

0

You've come across one of the many little quirks of PHP :).

Prior to PHP 5.5, empty works only on variables (more info on the manual page). This means you need to first assign $url->fragment(0) to something:

$fragment = $uri->fragment(0);
$module = empty($fragment) ? 'index' : $fragment;

Since existence isn't an issue, you don't actually need empty here (since empty($var) is equivalent to isset($var) && $var):

$module = $uri->fragment(0) ? $uri->fragment(0) : 'index';

In this situation it won't matter, but as a general piece of advice, be careful using empty with strings. It can have a few "wtf?" moments in corner cases. For example, all forms of 0 are considered empty (0, "0", 0.0).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.