Page 1 of 1

Calling a function within a case statement

Posted: Sat Sep 06, 2008 6:52 am
by treesa
How do we call a function within a swtitch statement in php?For one of the case options,
is it possible to call a function.If so where exactly we need to place the php function?
Have tried this option but it displays error when executing it?


Thanks

Re: Calling a function within a case statement

Posted: Sat Sep 06, 2008 7:31 am
by JAB Creations
I'd try something like this...

Code: Select all

<?php
switch ($i) {
case 0:
    my_function1();
    break;
case 1:
    my_function2();
    break;
case 2:
    if (my_function1() == "2") {// might be able to do this too, not sure};
    break;
}
?>
I don't usually use case however.

A function can be referenced almost like a variable...

Code: Select all

echo $my_var;
echo $my_function();
 
if ($my_var == "1") {//execute if equal to 1}
if ($my_function() == "1") {//execute if function returns 1}
 

Re: Calling a function within a case statement

Posted: Sun Sep 07, 2008 1:56 am
by treesa
thanks,
but can this be done?

<?php
switch ($i)
{
case 0:
$var1=my_function1(); break;
case 1:
my_function2();
break;
case 2:
if (my_function1() == "2") {// might be able to do this too, not sure};
break;
}

my_function1()
{
<code here>
return $output

}
?>


Is the portion which ive hightlighted in blue colour valid?this is what i need to do.

Re: Calling a function within a case statement

Posted: Sun Sep 07, 2008 5:03 am
by JAB Creations
Have you attempted to do something? Did you encounter an error? Is something not executing the way you expected? Once you've tried something and you encounter a snag between you and your goal then post your question. To recieve an answer you need to state your goal and the issue you've encountered before for anyone to be able to help you.

Re: Calling a function within a case statement

Posted: Sun Sep 07, 2008 10:22 pm
by treesa
thanks,
but can this be done?

<?php
switch ($i)
{
case 0:
$var1=my_function1($str); break;
case 1:
my_function2();
break;
case 2:
if (my_function1() == "2") {// might be able to do this too, not sure};
break;
}

my_function1($str)
{
<code here>
return $output;
}

?>

after adding the coloured statements,i get the internal server error.
bofore using function ,whatever is inside the function my_function1, i used those statements
within the case statements.then it was working fine. after adding the function , i get internal server error.

Re:Calling a function within a case statement

Posted: Mon Sep 08, 2008 12:34 am
by treesa
function is working now.