PHP Singleton Class - Fatal error: Call to private MyObject::__construct() -
singleton class:
<?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 oci_* instance private function __construct() { } // block directly instantiating private function __clone() { } // block cloning of object public static function call() { // create instance if not exist if(!isset(self::$instance)) { // oracle_* constants should set or // replaced 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 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; } } ?>
when try using singleton
class below code, works perfect , fetch results.
$conn = db_singleton::call(); $stid = oci_parse($conn, 'select * somevalid_table'); oci_execute($stid); while($result=oci_fetch_array($stid,oci_assoc+oci_return_nulls)) { $result_set_array[] = $result; }
now, when try extending class using model, throws exception
class myclass extends db_singleton{ public function somemodel() { $result = parent::queryresult(" select * somevalid_table"); return $result; } }
exception:
fatal error: call private db_singleton::__construct() context 'somecontroller'
i know class cannot instantiated having private constructor. __construct() functions called when object instantiated, trying $x = new myobject() cause fatal error private construction function.
i using singleton
classes prevent direct instantiation of object. how can overcome issue ? best solution ?
thanks.
$x = new myobject()
never work if constructor private in class because __construct()
first method invoked on object creation.
create public method /** * singleton class * */ final class userfactory { /** * call method singleton * * @return userfactory */ public static function instance() { static $inst = null; if ($inst === null) { $inst = new userfactory(); } return $inst; } /** * private ctor nobody else can instance * */ private function __construct() { } }
to use:
$fact = userfactory::instance(); $fact2 = userfactory::instance(); $fact == $fact2;
but:
$fact = new userfactory()
Comments
Post a Comment