单例类:PHP Singleton类 - 致命错误:调用私有的MyObject :: __结构()
<?php
class db_singleton
{
const ORACLE_HOST = "SOMEIP";
const ORACLE_USER = "validuser";
const ORACLE_PASS = "validpass";
const ORACLE_DB = "SOMEIP/DBNAME";
private static $instance; // stores the oci_* instance
private function __construct() { } // block directly instantiating
private function __clone() { } // block cloning of the object
public static function call()
{
// create the instance if it does not exist
if(!isset(self::$instance))
{
// the ORACLE_* constants should be set to or
// replaced with your db connection details
self::$instance = oci_connect(self::ORACLE_USER, self::ORACLE_PASS, self::ORACLE_DB);
if(self::$instance->connect_error)
{
throw new Exception('Oracle connection failed: ' . self::$instance->connect_error);
}
}
// return the instance
return self::$instance;
}
public function __destruct() {
oci_close($instance);
}
public function queryresult($query)
{
$result_set_array =array();
$this->stmt = oci_parse($this->con, $query);
oci_execute($this->stmt);
while($row=oci_fetch_array($this->stmt,OCI_ASSOC+OCI_RETURN_NULLS))
{
$result_set_array[] = $row;
}
oci_free_statement($this->stmt);
return $result_set_array;
}
}
?>
当我尝试使用singleton
类下面的代码,它可以完美运行,并获取结果。
$conn = db_singleton::call();
$stid = oci_parse($conn, 'SELECT * FROM somevalid_table');
oci_execute($stid);
while($result=oci_fetch_array($stid,OCI_ASSOC+OCI_RETURN_NULLS))
{
$result_set_array[] = $result;
}
现在,当我尝试使用模型扩展我的课,它会抛出异常
class Myclass Extends db_singleton{
public function someModel()
{
$result = parent::queryresult(" select * from somevalid_table");
return $result;
}
}
例外:
Fatal error: Call to private db_singleton::__construct() from context 'someController'
我知道,类不能有私有构造函数实例化。 __construct()函数总是在实例化对象时调用,所以试图执行类似$ x = new MyObject()将导致私有构造函数的致命错误。
我正在使用Singleton
类来防止直接实例化一个对象。我该如何克服问题?什么是最好的解决方案?
谢谢。
向你的子类添加一个空构造函数。这将覆盖私有的父类构造函数。 – 2014-12-02 07:37:57
它会影响单身模式吗? – Slimshadddyyy 2014-12-02 07:41:13
如果你想真正的单身人士行为不扩展单身人士类。 – 2014-12-02 07:48:55