Fix: PHP Fatal error: Function name must be a string.

This is a short guide on how to fix the following fatal error in PHP:

Fatal error: Function name must be a string

At first, you might think that your PHP code contains a function that hasn’t been named properly. However, that isn’t actually the case. Instead, this error means one of two things:

  1. You are attempting to reference an array as if it were a function.
  2. You are trying to reference an anonymous function that does not exist.

Incorrectly referencing an array.

Take a look at the following example:

In the code snippet above, I am attempting to reference a key called “page” inside the $_GET array. However, I have made the mistake of using rounded brackets instead of square brackets.

Remember: Rounded brackets are for function calls and square brackets are for referencing array keys.

As a result, a fatal error will be thrown. Why? Because $_GET is an array, not a string. Therefore, we can not use it as a function call.

In PHP, if you want to reference an array element, you must use square brackets. Therefore, in order to fix this error, we must replace our rounded brackets with square brackets:

This error is particularly common among beginner developers who are attempting to reference superglobal arrays such as $_GET, $_POST, $_FILES, $_SESSION and $_COOKIE.

Here is another example, this time with the $_SESSION array:

This error will also occur if you incorrectly reference a custom array:

If you run the PHP code above on your own server, you will encounter the following:

Fatal error: Function name must be a string in /path/to/your/file.php on line 10

This is because we attempted to reference our array using rounded brackets. The fix in this case is to simply use square brackets instead:

Referencing an anonymous function that doesn’t exist.

In PHP, you can also create anonymous functions and then reference them like so:

The above piece of code works because we assigned a function to the variable $anonFunction.

However, if we mess up and attempt to reference an anonymous function that does not exist, our code will spit out a fatal error:

Here, you can see that I have a typo in my variable name. As a result, the variable equates to null and a fatal error is thrown. Why? Because a function name must be a string. It cannot be a null value.

Hopefully, this guide helped you to fix your error!

Facebook Comments