l2aelba
l2aelba

Reputation: 22167

to Global Variables inside functions

I have problem to Global Variables inside functions

<?php
    function main(){
        $var = "My Variable";
        function sub() {
            GLOBAL $var;
            echo $var; // Will show "My Variable"
        }
        sub();
        echo $var; // Will show "My Variable" 
    }
    main();
    sub(); // Will not show and I will sub() cant use outside main() function
?>
  1. I just want to global $var inside sub functions
  2. sub() will not work outside main() function

I tied to use GLOBAL but it show nothing ... Any ?

Upvotes: 0

Views: 279

Answers (2)

Dodge
Dodge

Reputation: 8297

Not sure if i understand what you want, but your $var is not global. its a local variable inside main()

a variable is only global, if you declare it outside of a function or class.

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

why would you declare a method inside a method to call it from there?

maybe something like this is what you want...

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

Upvotes: 1

VolkerK
VolkerK

Reputation: 96159

You do not assing a value to the global scope variable $var.
Only main() assigns a value to a variable called $var but only in main()'s scope. And only main()'s echo $var; actually prints the value. Both calls to sub() do not produce output.
try it with

<?php
function main(){
    $var = "My Variable"; 
    function sub() {
      GLOBAL $var;
      echo 'sub: ', $var, "\n";
    }
    sub();
    echo 'main: ', $var, "\n";
}
main();
sub();

the output is

sub: 
main: My Variable
sub: 

and please have a read of https://en.wikipedia.org/wiki/Dependency_injection ;-)

Upvotes: 1

Related Questions