Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why defining a function count as more than one statement?

I saw a strange behaviour in PHP. See this example:

<?php
if (true)
    function my_function(){
        echo "here";
    }

my_function();
?>

Running this will give an error:

Parse error: syntax error, unexpected 'my_function' (T_STRING), expecting '(' on line 4

I found that the fix to this error is to add parenthesis:

<?php
if (true) {
    function my_function(){
        echo "here";
    }
}
my_function();
?>

This code will run properly.

Can you explain it? Why defining a function count as more than one statement?

like image 380
zvi Avatar asked Jul 12 '26 04:07

zvi


1 Answers

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.

like image 119
Dharman Avatar answered Jul 14 '26 05:07

Dharman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!