【问题标题】:$this->a->b->c->d calling methods from a superclass in php$this->a->b->c->d 从 php 中的超类调用方法
【发布时间】:2009-04-12 17:45:11
【问题描述】:

你好,我想在课堂上做点什么

我想做一个超类,我的所有类都在它上面扩展

            ____  database class
           /
chesterx _/______  member class
          \
           \_____  another class   

我想像这样调用数据库类中的方法

$this->database->smtelse();



class Hello extends Chesterx{

  public function ornekFunc(){
     $this->database->getQuery('popularNews');
     $this->member->lastRegistered();
  }

}  

当我将我的超类扩展到任何类时,我想用它的父类名调用一个方法

【问题讨论】:

    标签: php oop


    【解决方案1】:

    我不太清楚你最后一句话是什么意思,但这是完全正确的:

    class Chesterx{
     public $database, $member;
     public function __construct(){
       $this->database = new database; //Whatever you use to create a database
       $this->member = new member;
     }
    }
    

    【讨论】:

      【解决方案2】:

      考虑单例模式 - 它通常更适合数据库交互。 http://en.wikipedia.org/wiki/Singleton_pattern

      【讨论】:

      • 我很想知道为什么。
      【解决方案3】:

      您也可以考虑使用方法来获取子对象 这样做的好处是对象在需要之前不会被初始化,并且还提供了更松散耦合的代码,让您可以更轻松地更改数据库的初始化方式。

      class Chesterx{
         public $database, $member;
      
         public function getDatabase() {
             if (!$this->database ) {
                 $this->database = new database; //Whatever you use to create a database
             }
             return $this->database;
         }
      
         public function getMember() {
             if (!$this->member) {
                 $this->member = new member;
             }
             return $this->member;
         }
      

      }

      【讨论】:

        猜你喜欢
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-27
        • 1970-01-01
        相关资源
        最近更新 更多