0

$this->a->b->c->d 从 php 中的超类调用方法

我在这个链接上问了一个问题我对这个技术有问题我可以从一个类中调用子类

像这样

$chesterx->db->query();

我想从子班再上一班

例如

我想查询来自 sql 类的执行

            ROOT
             |
sql <---  chesterx --->  db

我想使用 db 中的 sql 类

我无法从 db 类返回chesterx 类的问题

/编辑/

我有一些类,如新闻、成员、类别、数据库和查询

我喜欢主题顶部的链接

公共函数 __construct(){

    function __construct(){  
      if(!$this->db){                                       
                 include(ROOT."/func/class/bp.db.class.php");
                 $this->db = new db;
            }
if(!$this->chester){                                        
                 include(ROOT."/func/class/bp.chester.class.php");
                 $this->db = new chester;
            }
        }

我用这段代码调用了 db 类,现在我可以很好地调用和使用 db 类方法

例如

我想使用 db 的方法

该方法包含一个从chester 类的方法返回数据的值

我希望我能澄清自己/编辑/

有没有办法做到这一点?

4

2 回答 2

3

下面的代码片段可能是一个解决方案,尽管我不太喜欢循环引用。试一试,并在你认为合适的时候使用它。顺便说一句,您所说的 class 和 subclass 实际上是包含和包含的 class

class Database
{
    public $chesterx;

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

class Sql
{
    public $chesterx;

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

class Chesterx
{
    public $db;

    public $sql;

    public function __construct()
    {
        $this->db  = new Database($this);
        $this->sql = new Sql($this);
    }
}
于 2009-04-24T15:26:48.320 回答
3

我发现 Ionut G. Stan 的解决方案适合您的情况,但您可能还想考虑factory/singleton 模式,尽管只有当您的chesterx 类是全局类并且只调用一次时它才有用

于 2009-04-24T22:34:53.800 回答