Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function inside an if structure

Tags:

can I put a function in PHP inside a if structure? like this:

<?php
    if(true){
         function HelloWorld(){
             echo "Hello World!!!";
         }
         HelloWorld();
    }
?>

because I have tried and it works, but I don't know if it is correct or not. Thanks

like image 660
Cattani Simone Avatar asked May 06 '11 14:05

Cattani Simone


People also ask

Can I put a function inside an IF statement?

This is perfectly legal - it simply defines the function within the if statement block.

Can we use function in if?

Technical Details. Use the IF function along with AND, OR and NOT to perform multiple evaluations if conditions are True or False. The condition you want to test. The value that you want returned if the result of logical_test is TRUE.

Can you put a function in an if statement Python?

We start by defining a function that takes a single numerical parameter. We add an IF statement that would then check if the number is negative and return the appropriate message. Remember to indent before calling the return function, so this only happens when the condition of the IF statement is satisfied.

Can we call function inside if condition in JavaScript?

Answer 55ee2c5d9113cbdba6000063You will have to call the quarter() function with an argument so that the return-Value with the remainder 3 will result in zero. Javascript has the so-called modulo-operator if used it will return the rest-value.


2 Answers

This is perfectly legal - it simply defines the function within the if statement block. That said, quite why you'd want to do this is somewhat of a mystery.

It's also worth noting that this function will be available in the global scope (i.e.: outside of the if statement block), as...

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

See the PHP User-defined functions manual page for more information.

like image 198
John Parker Avatar answered Nov 11 '22 07:11

John Parker


As middaparka says, this is perfectly legal, but in terms of using it, you might want to check if a function exists before declaring it:

if (!function_exists("foo"))
{
    function foo()
    {
        return "bar";
    }
}
  • function_exists documentation
like image 21
Jimmy Sawczuk Avatar answered Nov 11 '22 07:11

Jimmy Sawczuk