Search code examples
phpglobal-variableslaravel-5.4vonage

How to declare global variable and initialization


how can i declare a global variable and initialize it? .

I have this situation, i am using NEXMO SMS APP in laravel and I have a global variable and I initialize it in my constructor, then i use the global variable in my public functions. After using it in my public functions, it says undefined variable. Why? . Please bare to help me, i am just a beginner.

Here is my code:

 class CheckVerify extends Controller {
         private $client;
         public function __construct() {
            $client = app('Nexmo\Client');    
        }

        public function mobile_verification($number) {                        

        $verification = $client->verify()->start([
            'number' => $number,
            'brand'  => 'Mysite'
        ]);
        }

        public function check_verify($code) {        
            $client->verify()->check($verification, $code);
        }
    }

Solution

  • This isn't a global variable, it's called a class property, which is defined in the class (see http://php.net/manual/en/language.oop5.properties.php)

    When accessing these types of variables, you have to tell PHP which object contains the variable your referring to, and when it's the current object you have to use $this. So you class should be something like...

    class CheckVerify extends Controller {
        private $client;
        public function __construct() 
        {
            $this->client = app('Nexmo\Client');    
        }
    
        public function mobile_verification($number) 
        { 
            $verification = $client->verify()->start([
                'number' => $number,
                'brand'  => 'Mysite'
            ]);
        }
    
        public function check_verify($code) 
        {        
            $this->client->verify()->check($verification, $code);
        }
    }
    

    As an extra option - consider rather than hard coding the value in the constructor ...

    $this->client = app('Nexmo\Client'); 
    

    Pass this in as a value to the constructor...

    public function __construct( $client ) {
        $this->client = $client;    
    }
    

    This is called dependency injection (DI) and allows much more flexibility.