Jack
Jack

Reputation: 203

How to pass variables between classes in PHP without extending

So, I've got my setup like this:

class System extends mysqli{

    function __construct(){
         //user variables such as $this->username are returned here
    }

}

$sys = new System();

class Design{

    function setting(){
        echo $sys->username;
    }

}

$design = new Design();

Yet the Design class doesn't echo the username. I can echo the username outside of the Design class, but not inside the design class. How can I go about this?

Upvotes: 2

Views: 3738

Answers (3)

Explosion Pills
Explosion Pills

Reputation: 191749

Everyone else's answer is fine, but you can inject the dependency on system very nicely:

class Design{

    private $sys;

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

    function setting(){
        echo $this->sys->username;
    }
}
$sys = new System;
$design = new Design($sys);

Upvotes: 5

wanovak
wanovak

Reputation: 6127

That's because $sys isn't in the scope of the Design class.

function setting(){
    $sys = new System();
    $sys->username;
}

should work, assuming that username is public.

Upvotes: -1

Naftali
Naftali

Reputation: 146300

Your Design class has no access to the $sys variable.

You have to do something like this:

class System extends mysqli{

    function __construct(){
         //user variables such as $this->username are returned here
    }

}

class Design{

    private $sys;

    function __construct(){
        $this->sys = new System();
    }

    function setting(){
        echo $this->sys->username;
    }

}

$design = new Design();

Upvotes: 1

Related Questions