2

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);
        }
    }
Tazbirul Haque
  • 233
  • 1
  • 3
  • 15
Jc John
  • 1,799
  • 2
  • 34
  • 69

1 Answers1

4

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.

Takamura
  • 302
  • 1
  • 4
  • 16
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55