Search code examples
phpscopeglobal-variables

Python supports global scope of variable but Php doesn't supports global scope variables inside a function without using the global keyword?


<?php
   $a ="helllo welcome to php! ....:)"; 
   function msg(){ 
       /* global $a; */
       echo $a;
   } 
   msg();
?>

Global variable $a is not accessible inside the function msg() but when i use global $a then it is accessible, i want to know that it is accessible or not without using global keyword inside or outside the function for the particular variable

Output

Code

✔ In python, it's accessible even without using the global keyword ✔
But it is supported in python even without using global keyword ==> see the output at the right


Solution

  • Why did you commented global $a ?

    <?php
       $a ="helllo welcome to php! ....:)"; 
       function msg(){ 
           global $a;
           echo $a;
       } 
       msg();
    ?>