mardi 19 novembre 2019

PHP- 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?

Aucun commentaire:

Enregistrer un commentaire