Are variables outside functions global variables?

<?php $foo = 1; function meh(){ // <-- $foo can't be accessed } 

This is not like a global variable. However, does it have flaws such as global things if it is out of function?

+6
source share
6 answers

Yes. They can be accessed from anywhere, including other scripts. They are a little better since you need to use the global to access them from within the function, which gives more clarity as to where they come from and what they do.

The global variables are applied to the minuses : but this does not immediately make them evil, as is often perceived in some OO languages. If they create a good solution, effective and understandable, then you are fine. There are literally millions of successful PHP projects that use global variables declared like this. The biggest mistake you can make is not to use them and make your code even more complex when it would be perfectly correct to use them in the first place .: D

+7
source

All variables defined outside of any function are declared in the global scope. If you want to access a global variable, you have two options:

  • Use the global keyword

     <?php $a = 1; $b = 2; function Sum() { global $a, $b; $b = $a + $b; } ?> 
  • Or use $ GLOBALS

     <?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } ?> 

    More details at http://php.net/manual/en/language.variables.scope.php

+7
source
 <?php $foo = 1; function meh(){ global $foo; // <-- $foo now can be accessed } ?> 
+5
source

The external function is sorted as a global scope (compared to C-like languages), but you have to do one thing to allow var access within the function:

 function meh(){ global $foo; // $foo now exists in this scope } 
+2
source

In your example, $foo is created as a variable in the global scope. (If your displayed script was included() from a different range of capabilities / methods.)

PHP has no real global variables. You must manually use it with the global $foo; operator global $foo; to access them. (In addition, “something global is bad” advises just that, advising badly.)

+2
source

If I understand your question correctly, there really should not be a problem. If you do not declare the variable as global, it will be limited to the area in which it is declared, in which case any php file must contain the above code. You can declare another $ foo variable in meh (), and that will be independent of the $ foo defined on the outside.

+2
source

Source: https://habr.com/ru/post/889802/


All Articles