0
I am studying PHP and reading the documentation I came across this example:
<?php
$makefoo = true;
/* Nos nao podemos chamar foo() daqui
porque ela ainda não existe,
mas nos podemos chamar bar() */
bar();
if ($makefoo) {
function foo()
{
echo "Eu não existo até que o programa passe por aqui.\n";
}
}
/* Agora nos podemos chamar foo()
porque $makefoo foi avaliado como true */
if ($makefoo) foo();
function bar()
{
echo "Eu existo imediatamente desde o programa começar.\n";
}
?>
I understood that the function will only come into existence if the condition is evaluated as true, but opened me some doubts, because what I believe to be normal (from what I see in scripts third party) is to define functions and decide which will invoke from conditional tests, but in this example of documentation the test will define whether the function will be declared or not, preventing it from being invoked later in negative case, which leads me to some doubts:
Is that considered good practice? Since the code I believe becomes more complex, because the rest of my code must be prepared to work perfectly even with the absence of this function.
Would you have any example of application? I’m the type who understands things more clearly with some example.
I personally don’t see any reason to call a function before it’s set. In my opinion it is counterintuitive and the code should be intuitive. In fact, what should be
bar
in his case?– Woss