0

I read somewhere that PHP first parses a file and then executes it's code. If this is true, why can't variables be used before definition/declaration, like functions?

echo testFunction();

function testFunction(){
    return "Hello ";
}

echo $testVar;

$testVar = "there!";

This code will print "Hello" and a notice, "Undefined variable: testVar".

Tiberiu
  • 418
  • 1
  • 3
  • 12
  • https://stackoverflow.com/questions/5467990/does-function-definition-order-matter should answer the one part. – Nigel Ren May 07 '19 at 15:55
  • But what about the variable part? – Tiberiu May 07 '19 at 15:57
  • 4
    Because during parsing the code is not actually executed. So, the function is parsed and build, but nothing is done with it yet, where as assigning a value to a variable is only done during execution. – KIKO Software May 07 '19 at 15:58
  • Code would get very confusing if you could do things like that. Consider `$testVar="1"; echo $testVar; $testVar="2";`... – HardcoreHenry May 07 '19 at 16:00

1 Answers1

1

so I know the variables have to be always defined before they are used, this is a precipio of programming, so if it is a principle is how they should be made, are rules. We can interpret this as "laws" of programming.

the function is a module that will be executed when called for example if inside a function I have a code to delete files always click the button, this function will only be called when the button is clicked, otherwise it is not executed, in the case of variable, we can not use it to show its contents if it has not yet been initialized with something

NoobDEV-GBL
  • 354
  • 3
  • 20