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
This is perfectly legal - it simply defines the function within the if statement block.
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.
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.
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.
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.
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
documentationIf 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