Posted in Code Snippets, PHP

PHP: Only variables should be passed by reference

Often times developers end up with this error:

Notice: Only variables should be passed by reference in <file_name>.php on line <line_number>

This is due to one of the reason that you need to pass a real variable and not a function that returns an array. It is because only actual variable may be passed by reference.

Example:

$string = "this-is-a-sample-text";
echo end(explode('-', $string));

This renders the above notice. From the PHP Manual for end​ function, we can read this:

The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference.

Here, we expect to print text, which is the last exploded element. It does print but with this notice. To fix this, one need to split into two lines:

$string = "this-is-a-sample-text";
$strings = explode('-', $string);
echo end($strings);

This is how you need to manage the notice. Some turns off the notice using PHP error_reporting function which is not advisable.

 

 

 

 

Advertisements

One thought on “PHP: Only variables should be passed by reference

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s