Search code examples
phpoopglobal-variablesprivate

How do declare global variable in PHP class


class Auth extends Controller {

    function __constructor(){
        private $pass;
    }
    function Auth()
    {
        parent::Controller();   
        $this->load->library('session');
        $this->load->helper('cookie');
        $this->load->library('email');
    }
    function index(){
            ..........
    }
    function loging(){
                $this->pass = "Hello World";
    }
    function test(){
                 var_dump($this->pass); // this is on the  line 114
    }
}

When I access the test function I get this error:

Parse error: syntax error, unexpected T_PRIVATE in /var/www/clients/client1/web15/web/application/controllers/auth.php on line 6

instead of the string "Hello World". I wonder why ? Can anyone help me with this ? Thx in advance


Solution

  • First up, you're not trying to create a "global variable" (as your title suggests), but a private member variable.

    In order to do that you need to declare the private member variable outside of the constructor:

    class Auth extends Controller {
    
        private $pass;
    
        function __construct(){
        }
    
        function auth()
        {
            parent::Controller();   
            $this->load->library('session');
            $this->load->helper('cookie');
            $this->load->library('email');
        }
        function index(){
                ..........
        }
        function loging(){
            $this->pass = "Hello World";
        }
        function test(){
            echo $this->pass;
        }
    }
    

    Also:

    • Correct the name of your constructor
    • Chose a naming convention (e.g. lowercase first character of function names) and stick to it.

    As a trivial answer / example of what you are asking. Try this:

    <?php
    
        class Auth {
    
            private $pass;
    
            function __construct(){
            }
    
            function loging(){
                $this->pass = "Hello World";
            }
            function test(){
                echo $this->pass;
            }
        }
    
        $oAuth = new Auth();
        $oAuth->loging();
        $oAuth->test();
    
    ?>
    

    It outputs:

    C:\>php test.php
    Hello World