另一个类内的PHP访问类 [英] PHP access class inside another class

查看:48
本文介绍了另一个类内的PHP访问类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有两个这样的类:

So I have two classes like this:

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

我想访问所有方法栏中的foo方法,而无需在bar内的每个方法中都声明它,就像这样:

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 */
}

我也不想扩展它.我尝试使用var关键字,但是它似乎没有用.为了访问bar所有方法中的另一个类"foo",我该怎么做?

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?

推荐答案

您也可以这样做:

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. */
}

稍后您可以做到:

$foo = new foo();
$bar = new bar($foo);

这篇关于另一个类内的PHP访问类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆