Function definition is not a statement.
You asked:
Why defining a function count as more than one statement?
It doesn't. Defining a function is not a statement.
From PHP Manual:
A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well.
An if
statement must be followed by another statement! Let's simplify your problem and see what are some examples of such statements as defined above:
if(1)
{} // A statement-group is a statement by itself as well.
if(1)
; // an empty statement
if(1)
$a=1; // an assignment
if(1)
print(1); // a function call
if(1)
while(0){} // a loop
if(1)
if(0); // a conditional statement
A definition of function or class is not a statement per the official PHP definition. A non-statement cannot be used in the context where a statement is expected.
When a function definition is a statement?
PHP 5.3 has introduced a concept of anonymous functions (Lambda Functions and Closures). An anonymous function definition is a statement.
The syntax of anonymous function is almost the same as the normal function definition, but you are expected to provide no name. In other words keyword function
must be followed by ()
with only whitespace allowed between them. It must also end in semicolon.
// This is valid:
if(1)
function (){};
//This is invalid:
if(1)
function a(){}
// ^
// syntax error, unexpected 'a' (T_STRING), expecting '('
This is why the error message is telling you that the name of the function is unexpected. PHP expects a statement and when it encounters function
keyword, it expects that you are defining an anonymous function. An anonymous function doesn't have a name, so the name part is unexpected.