开发者

Function called and declared within switch construct gives error

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 ($n开发者_运维技巧o)
{
case "1":
    test();
function test()
    {
    echo "Hello test";
        }
 }
?>


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.


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();
 }
?>


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.


A couple of problems. you need to use

 case 1:

for switches, otherwise it will be looking for a string equivalent to "1". "1" != 1 (the first is a string, the second an integer)

While your text did say functions could be defined anywhere, they didn't actually mean anywhere. You cannot define a function inside of a block of code, so you'l have to define the function outside of the switch:

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

function test()
{
    echo "I'm inside the test function!";
}

?>

Otherwise things just get crazy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜