Sarthak Batra
Sarthak Batra

Reputation: 597

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.

Upvotes: 0

Views: 2528

Answers (5)

Arvind Thasal
Arvind Thasal

Reputation: 11

declare variable $api in a class then only accessible to other function body

Upvotes: 0

Zhorov
Zhorov

Reputation: 29943

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.

Upvotes: 0

simonecosci
simonecosci

Reputation: 1214

you are calling parent::__construct(new PaymentModel); on a class which doeasn't extend any base class.

Upvotes: 0

Cody604
Cody604

Reputation: 162

To be able to use $this->api in your class, you will need to set it as an attribute.

so :

class Demo 
{
private $api;

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, as notified by other, you are to construct a parent class while your class 'Demo' does not extend any other class.

Upvotes: 1

Shardj
Shardj

Reputation: 1969

To access object variables you need to use $this. In your case change the first line in createOrder() to $order = $this->api->order->create();

Also you appear to be trying to run the classes parents constructor in your constructor. But the class doesn't have a parent.

Upvotes: 0

Related Questions