php - to Global Variables inside functions -


i have problem global variables inside functions

<?php     function main(){         $var = "my variable";         function sub() {             global $var;             echo $var; // show "my variable"         }         sub();         echo $var; // show "my variable"      }     main();     sub(); // not show , sub() cant use outside main() function ?> 
  1. i want global $var inside sub functions
  2. sub() not work outside main() function

i tied use global show nothing ... ?

not sure if understand want, $var not global. local variable inside main()

a variable global, if declare outside of function or class.

<?php     $var = "my variable"; // made $var global     function main(){         //removed $var here         function sub() {             global $var;             echo $var; // show "my variable"         }         sub();         echo $var; // throw notice:  undefined variable: var     }     main();     sub(); // show "my variable" ?> 

why declare method inside method call there?

maybe want...

<?php    //$var = "my variable";     function main(){         $var = "my variable";         $sub = function($var) {             echo "sub: ".$var; // show "sub: variable"         };         $sub($var);         echo "main: ".$var; //  show "main: variable"     }     main();     // sub(); // not work     // $sub(); // not work ?> 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -