Sam San
Sam San

Reputation: 6903

Global variables of function inside function of a class

class Someclass{

    function topFunction()
    {       

        function makeMeGlobal($var)
        {
            global $a, $b;

            $a = "a".$var;
            $b = "b".$var;
        }

        makeMeGlobal(1);    
        echo "$a <br>";
        echo "$b <br>";

        makeMeGlobal(2);    
        echo "$a <br>";
        echo "$b <br>";
    }
}

I am using that test code on codeigniter but nothings happen.

I suppose to print a result like this

a1
b1
a2
b2 

How to handle those functions inside a class?

Upvotes: 1

Views: 50

Answers (2)

MalikAbiola
MalikAbiola

Reputation: 33

you are creating the global variables inside the function, try creating them in the class scope rather than the function. that should work.

Upvotes: 0

h.s.o.b.s
h.s.o.b.s

Reputation: 1319

You declare globals inside function scope.

Try to declare them at class scope:

class Someclass{

    function topFunction()
    {       

        function makeMeGlobal($var)
        {
            global $a, $b;

            $this->a = "a".$var;
            $this->b = "b".$var;
        }

        makeMeGlobal(1);    
        echo $this->a . "<br>";
        echo $this->b . " <br>";

        makeMeGlobal(2);    
        echo $this->a . "<br>";
        echo $this->b . "<br>";
    }
}

Upvotes: 1

Related Questions