Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP access class inside another class

So I have two classes like this:

class foo {
    /* code here */
}
$foo = new foo();
class bar {
    global $foo;
    public function bar () {
        echo $foo->something();
    }
}

I want to access the methods of foo inside all methods bar, without declaring it in each method inside bar, like this:

class bar {
    public function bar () {
        global $foo;
        echo $foo->something();
    }
    public function barMethod () {
        global $foo;
        echo $foo->somethingElse();
    }
    /* etc */
}

I don't want to extend it, either. I tried using the var keyword, but it didn't seem to work. What do I do in order to access the other class "foo" inside all methods of bar?

like image 714
Waleed Khan Avatar asked May 19 '10 02:05

Waleed Khan


2 Answers

You could do like this too:

class bar {
    private $foo = null;

    function __construct($foo_instance) {
      $this->foo = $foo_instance;
    }

    public function bar () {
        echo $this->foo->something();
    }
    public function barMethod () {
        echo $this->foo->somethingElse();
    }
    /* etc, etc. */
}

Later you could do:

$foo = new foo();
$bar = new bar($foo);
like image 85
Sarfraz Avatar answered Oct 16 '22 15:10

Sarfraz


Make it a member of bar. Try to never use globals.

class bar {
    private $foo;

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

    public function barMethod() {
        echo $this->foo->something();
    }
}
like image 26
Tesserex Avatar answered Oct 16 '22 16:10

Tesserex