How to fix PHP Fatal error: Cannot use result of built-in function in write context

To fix the "Cannot use result of built-in function in write context" PHP Fatal Error, you first have to understand what is causing the problem. Note that the error message occurs when a built-in function or method (meaning, they are native functions that comes with PHP) that is expected to return a value is being used in a context, but the value cannot be written. For instance, you are trying to assign the value of a built-in function to a passed by reference variable, but the function does not return a value. This will trigger the error.

Common culprits of this error are the built-in functions func_get_args() and func_num_args(). Normally, these functions are called in an object function within a class (also known as function context). However, if you used them as a passed by reference value ie. $variable = &func_get_args() or $variable = &func_num_args, they would trigger the Cannot use result of built-in function in write context error.

In older versions of PHP, these errors don't exist as older versions seem to ignore this issue, but starting from PHP 7.2, you will start seeing this error message.

Example of the codes that trigger these issue are:

class testclass {
  public function testobjectfunc(){
    $arr = &func_get_args();
  }
}

In the code above, func_get_args(), a built-in function, does not return anything, but the function context is trying to extract a passed by reference value, thus, triggering the error.

The simple solution to the problem is to remove the passed by reference symbol — the ampersand (&), simply because you cannot write nothing into a passed by reference variable. It has to have something. Besides, in the code above, there is no point to used pass by reference as you are starting an array variable from a clean slate. You normally only use this method if you have an existing array with contents that you wanted to pass into a function.

This is how the code should look like:

class testclass {
  public function testobjectfunc(){
    $arr = func_get_args();
  }
}

To sum up, the fatal error can be fixed by ensuring that the built-in function in a context returns a value before using it as a passed by reference variable.

Leave a Reply

Your email address will not be published. Required fields are marked *