Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function called and declared within switch construct gives error

Tags:

php

I am new to PHP. Well the text i am referring to say quotes
Functions can be defined anywhere within your program.

the above statement holds fine for code block 1 but not for code block 2. KINDLY EXPLAIN?

CODE Block 1:

<?php
test();
function test()
{
    echo "Hello Inside the function";
}
?>

CODE Block 2:

<?php
$no=1;
switch ($no)
{
case "1":
    test();
function test()
    {
    echo "Hello test";
        }
 }
?>
like image 585
dkjain Avatar asked Sep 04 '11 15:09

dkjain


3 Answers

In theory, yes, functions can be defined "anywhere". In practice, there's a trick to it. The trick is as follows: when PHP reads and compiles the source of your script, it looks for function definitions, and if function definition is in global context (not inside if, switch, etc.) it will be defined immediately. However, if it is inside such construct, or inside another function, etc. it will be defined only when control passes the line on which function() statement resides.

Thus, code block 1 works - because the function is in global context, so PHP will define it before any code is run. But in code block 2, the function is in the context of switch, so it will be defined only when control passes line 7. But since you try to call it on line 6, it is not defined yet! So PHP errors out.

The advice here is never define your functions inside conditionals etc. unless you mean it to be conditional definitions - and then take care not to call them before they are defined.

like image 124
StasM Avatar answered Oct 02 '22 17:10

StasM


You can declare function in switch statement, but it's not so good. Your have error because you call function and just then declare it. At first you should declare function and then use it.

<?php
$no=1;
switch ($no)
{
    case "1":
        function test()
        {
            echo "Hello test";
        }
        test();
 }
?>
like image 44
pleerock Avatar answered Oct 02 '22 16:10

pleerock


You cannot declare a function in a switch statement.

However what you can do is the following:

<?php
$no=1;
switch ($no)
{
    case "1":
        test();
        break;
}

function test()
{
    echo "Hello test";
}
?>

Just remove the function from the switch.

The function only gets executed when called so it doesn't matter.

EDIT

What propably is meant by that quote (Functions can be defined anywhere within your program.) is:

You can declare functions before or even after you call them in your script.

like image 45
PeeHaa Avatar answered Oct 02 '22 17:10

PeeHaa