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";
}
}
?>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With