phpclassconstructorclass-constructors

php constructor variable not getting accessed in the functions below


I have initialized a new instance of a library in the __construct(){} method of a PHP class and equated it to a variable,

but now I want to use this variable to access methods of the library inside another function but PHP is not allowing me do that.

class Demo 
{

public function __construct()
    {

    parent::__construct(new PaymentModel);

    $this->api = new Api(config("razorpay", "key_id"), config("razorpay", "key_secret"));

    }

public function createOrder()
  {
    $order = $api->order->create();
    echo '<pre>';
    var_dump($order); die;

  }
}

I looked at the __construct documentation and some other answers here on stack overflow but all they did was confuse me more than helping me out.

Please help me figure this out as I am a starter myself in tech.


Solution

  • You have defined api as a class variable (property). Use $this->api to acces this class variable (property) in other methods of your class.

    // This class probably inherits some base class
    class Demo extends BaseDemo 
    {
    
    public function __construct()
        {
    
        parent::__construct(new PaymentModel);
    
        $this->api = new Api(config("razorpay", "key_id"), config("razorpay", "key_secret"));
    
        }
    
    public function createOrder()
      {
        $order = $this->api->order->create();
        echo '<pre>';
        var_dump($order); die;
    
      }
    }
    

    Also check your class definition - if parent::__construct() is called, then your class probably inherits some base class. If this is not the case, remove parent::__construct() call.