J.Adams
J.Adams

Reputation: 133

Instantiate global class inside another class

I need to access a class within several functions of my main class and I don't want to instantiate the class within each. I would instead like to create a global variable pointing to a new instance of Class2. How can I achieve this in PHP? Code:

Class Main 
{
    public $l = new Class2();

    public function f1()
    {
         $this->$l->getData();
    }

    public function f1()
    {
         $this->$l->getData();
    }
}

ERROR:

Symfony \ Component \ Debug \ Exception \ FatalThrowableError
(E_ERROR) Cannot access empty property

I also tried :

public $l;

public function __construct()
{
    $this->$l = new Class2();
}

Upvotes: 0

Views: 153

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

Drop the dollar sign,

public $l;

public function __construct()
{
  $this->l = new Class2(); // no $
}

When access a class property you don't need the dollar sign in front of the variable.

Upvotes: 1

Related Questions