Search code examples
phpclassglobal-variables

unable to call global variables inside a function class


I am new to PHP5 and classes, am struggling with being able to get global variable to work when inside a function, to better explain it please check the code bellow.

class alpha{

#first function
public function n_one(){

    #variable
    $varr = 1;

    #inner function
    function n_two(){
        global $varr;

        #Unable to get variable
        echo $varr;
        if($varr)
        {
            echo 'yessssss';
        }
    }

    echo $varr // Returns variable fine
}
}

I seem to be doing something wrong violating how classes and functions work, can't figure what is it.


Solution

  • Move the 'inner function', and the property.

    class Alpha
    {
        private $varr = 1;
    
        public function n_one()
        {
            // to access a property ore another method, do this
            $this->varr = $this->doSomething();
    
            return $this->varr; // Returns variable fine
        }
    
        private function doSomething()
        {
            // manipulate $this->varr here
        }
    }
    

    Also, don't ever echo from within the class, instead return the variable and echo it.

    echo $alpha->n_one();