【问题标题】:Calling Parent Class From Sub Class PHP从子类 PHP 调用父类
【发布时间】:2010-10-21 15:21:52
【问题描述】:

$this->a->b->c->d calling methods from a superclass in 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 类的方法返回数据的值

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

有没有办法做到这一点?

【问题讨论】:

  • 您需要重新表述一下您的问题。我真的不明白。
  • 对不起,我不知道你在问什么......你能澄清一下吗?
  • 同意,这里有一个代码示例会非常有帮助。

标签: php oop non-english


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    下面的 sn-p 可能是一个解决方案,虽然我不太喜欢循环引用。试试看,并在你认为合适的时候使用它。顺便说一句,你所说的类和子类实际上是包含和包含类

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-13
      • 2010-12-29
      • 2012-02-22
      • 2023-02-26
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多