导致问题的系统的另一部分,问题已经解决
public static function getParticpantsIdsWithTitles(array $proftitlecodes)
{
//connect_mysqli is a singleton, but everytime this is called a new instance is created
$sqlconn = connect_mysqli::get_instance();
}
//All of these method calls cause the constructor of connect_mysqli to run
Participant::getParticpantsIdsWithTitles(array(1,2,3));
Participant::getParticpantsIdsWithTitles(array(1,2,3));
从静态函数中使用它时,是否存在一些我不了解单例的规则?每次都会创建一个新的mysqli_object。 (仅限静态函数)。它可以从非静态函数中正常工作。
private static $instance = FALSE;
var $host ;
var $dbUser ;
var $dbPass ;
var $dbName ;
var $dbConn ;
var $dbconnectError ;
var $query;
var $result;
var $row;
function __construct ()
{
$this->host = 'host' ;
$this->dbUser = 'user' ;
$this->dbPass = 'password' ;
$this->dbName = 'db' ;
$this->dbConn = new mysqli($this->host , $this->dbUser , $this->dbPass, $this->dbName ) ;
file_put_contents("/Library/WebServer/Documents/test.txt", "CONNECT\n", FILE_APPEND);
if ( !$this->dbConn )
{
trigger_error ('could not connect to server' ) ;
$this->dbconnectError = true ;
}
}
public static function get_instance()
{
if(!self::$instance)
{
self::$instance = new connect_mysqli();
}
return self::$instance;
}
答案 0 :(得分:0)
我无法重现你的问题。以下代码打印
创建了一个新的connect_mysqli
一次。
class foo
{
public static function getParticpantsIdsWithTitles(array $proftitlecodes)
{
$sqlconn = connect_mysqli::get_instance();
}
}
class connect_mysqli
{
private static $instance = FALSE;
public function __construct()
{
echo "A new connect_mysqli was created\n";
}
public static function get_instance()
{
if(!self::$instance)
{
self::$instance = new connect_mysqli();
}
return self::$instance;
}
}
for ($i = 0; $i < 10; ++$i)
{
foo::getParticpantsIdsWithTitles(array());
}
答案 1 :(得分:0)
我无法重现你的问题,但我确实注意到你的单身人士:
function __construct ()
这会将__construct()
方法默认为public
可见性。通常,单例的构造函数将被标记为private
,以防止在提供的get_instance()
方法之外进行实例化。
您确定只使用get_instance()
而从不执行$mysqli = new connect_mysqli()
之类的操作吗?您是否还确定不是从单例之外的上下文创建数据库连接?