php singleton局部变量在调用第二个方法时会丢失值

时间:2011-07-19 10:53:06

标签: php singleton

我有简单的单例,在第一组中设置工厂类的pdo对象 pdo对象很好地选择它的值。但是当我调用单例第二种方法(设置sql调用)时,我看到没有设置pdo对象。 这是示例代码: 单身人士课程:

<?php
require_once ('DBFactory.php');
require_once ('Config.php');

class DBHandler {

    private static $instance;
    private $pdo = NULL;

    private function __construct()
    {



    }

    public function ConnectToDb($db_name)
    {
        $ConfigObj = new Config();
        $SelectedDbConfig = $ConfigObj->GetSelectedDB($db_name);
        $pdo = DBFactory::GetDBConnection(Config::DB_TYPE_MYSQL,$SelectedDbConfig["host"],
                                                                 $SelectedDbConfig["db"], 
                                                                 $SelectedDbConfig["user"],
                                                                 $SelectedDbConfig["pass"]);

        if(!isset($pdo))
            return false;

       return true;

    }

    public function SetUserNameAndPass($user,$pass)
    {
        $query_add_user = "INSERT INTO (name ,password) values ('$user' , '$pass') ";
        if(!$this->ExecQuery($query_add_user))
        {
            echo "sql failed";
        }
    }


    public function ExecQuery($query_str)
    {

        $statment_handler = $this->pdo->prepare($query_str);
        if(!$statment_handler) {
            throw new ErrorException($this->pdo->error, $this->pdo->errno);
        }
        if($statment_handler->execute())
            return true;

        return false; 
    }
    public static function GetInstance()
    {
        if (!isset(self::$instance)) {

            $className = __CLASS__;
            self::$instance = new $className;
        }
        return self::$instance;
    }
}

?>

在这里我设置并调用单声道并在SetUserNameAndPass方法中获取  致命错误:在错误的非对象上调用成员函数prepare() 在检入调试器后,我可以看到pdo对象是空的。

<?php
require_once ('DBFactory.php');
require_once ('Config.php');

class DBHandler {

    private static $instance;
    private $pdo = NULL;

    private function __construct()
    {



    }

    public function ConnectToDb($db_name)
    {
        $ConfigObj = new Config();
        $SelectedDbConfig = $ConfigObj->GetSelectedDB($db_name);
        $pdo = DBFactory::GetDBConnection(Config::DB_TYPE_MYSQL,$SelectedDbConfig["host"],
                                                                 $SelectedDbConfig["db"], 
                                                                 $SelectedDbConfig["user"],
                                                                 $SelectedDbConfig["pass"]);

        if(!isset($pdo))
            return false;

       return true;

    }

    public function SetUserNameAndPass($user,$pass)
    {
        $query_add_user = "INSERT INTO (name ,password) values ('$user' , '$pass') ";
        if(!$this->ExecQuery($query_add_user))
        {
            echo "sql failed";
        }
    }


    public function ExecQuery($query_str)
    {

        $statment_handler = $this->pdo->prepare($query_str);
        if(!$statment_handler) {
            throw new ErrorException($this->pdo->error, $this->pdo->errno);
        }
        if($statment_handler->execute())
            return true;

        return false; 
    }
    public static function GetInstance()
    {
        if (!isset(self::$instance)) {

            $className = __CLASS__;
            self::$instance = new $className;
        }
        return self::$instance;
    }
}

?>



<?php
require_once ('DBHandler.php');

//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$user = ($_GET['user']) ? $_GET['user'] : $_POST['user'];
$password = ($_GET['password']) ?$_GET['password'] : $_POST['password'];


//flag to indicate which method it uses. If POST set it to 1
if($_POST)
{
    $post=1;
}

//Simple server side validation for POST data, of course, you should validate the email
if (!$user) $errors[count($errors)] = 'Please enter your user.';
if (!$password) $errors[count($errors)] = 'Please enter your password.';
$DBhandler_st = NULL;
 if (!$errors) {

     if ($_POST) {
        $DBhandler_st = DBHandler::GetInstance();
        if($DBhandler_st->ConnectToDb("db1"))
        {

            $user = trim($user);
            $password = trim($password);
            $DBhandler_st->SetUserNameAndPass($user,$password);
            echo '1';
        }
        else {
            echo '0';
        }

     }


} else {
    //display the errors message
    for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';
    echo '<a href="admin.html">Back</a>';
    exit;
}

?>

1 个答案:

答案 0 :(得分:1)

您创建局部变量$ pdo,而不是设置类变量。

使用self :: $ pdo =