【问题标题】:How to expend a super class object to a sub class in php?如何将超类对象扩展到php中的子类?
【发布时间】:2020-07-15 20:12:54
【问题描述】:

我想在数据库超类中实现单例。 但我想在子类对象上调用它的方法

超类:

class Database {

    private $conn;

    public static $instance;

    private function __construct($conn)
    {
        $this->conn = $conn;
    }

    public static function getInstance($conn)
    {
        if (!self::$instance) {
            self::$instance = new Database($conn);
        }
        return self::$instance;
    }
}

sub class:

class Article extends Database
{
public function __construct($conn)
{

        parent::getInstance($conn);
}
}

--->

$article = new Article($conn); 

但是 $conn 属性没有被初始化。 有没有直接调用超类构造函数并保持超类单例设计模式的成功方法?谢谢

【问题讨论】:

    标签: php inheritance singleton


    【解决方案1】:

    在 Singleton 中,您通过调用其静态方法 getInstance() 来实例化该类,并发送参数以建立与数据库的连接,建立连接并将其分配给非静态变量 $conn

    class Database {
    
        // Private to ensure you can get instance only by the static method
        private static $instance;
        
        // $conn is not static
        private $conn;
    
        private function __construct()
        {
            // Declared to avoid non-static instatiation
        }
    
        public static function getInstance($host, $user, $pass)
        {
            if (!self::$instance) {
                self::$instance = new self();
                // Connect to database
                self::$instance->$con = new PDO($host, $user, $pass);
            }
            return self::$instance;
        }
    }
    

    __construct() 和 getInstance() 已经在父类中定义了,不需要覆盖它们

    class Article extends Database
    {
        public function prepare($query)
        {
            return $this->conn->prepare($query);
        }
    }
    

    实例化模型并开始做一些事情:

    $article = Article::getInstance("mysql:host=localhost;dbname=mydatabase;charset=UTF8", 'myuser', 'mypass');
    $stmt = $article->prepare('SELECT * FROM sometable');
    

    【讨论】:

      猜你喜欢
      • 2016-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多