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:
- You are attempting to reference an array as if it were a function.
- You are trying to reference an anonymous function that does not exist.
Incorrectly referencing an array.
Take a look at the following example:
//This will cause a fatal error if($_GET('page') >= 1){ //do something }
In the code snippet above, we are attempting to reference a key called “page” inside the $_GET array. However, we 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. This is 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. In order to fix this error, we must replace our rounded brackets with square brackets:
//A fixed version if($_GET['page'] >= 1){ //do something }
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 will fail echo $_SESSION('name');
This error will also occur if you incorrectly reference a custom array:
<?php //An example array $myArray = array( 'Cat', 'Dog', 'Horse' ); //Attempting to print out the //first element echo $myArray(0);
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:
//Doing it the right away. echo $myArray[0];
Referencing an anonymous function that doesn’t exist.
In PHP, you can also create anonymous functions and then reference them like so:
//Creating an anonymous PHP function $anonFunction = function(){ echo 'Hello World!'; }; //Calling said function $anonFunction();
The above piece of code works because we assigned a function to the variable $anonFunction.
However, if we make a mistake and reference the function by the wrong name, our code will spit out a fatal error:
//There is a typo in my //variable name $anoFunction();
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. This is because a function name must be a string. It cannot be a null value.