通过类的函数将变量传递给PHP类构造函数

时间:2016-02-12 01:22:08

标签: php function class pdo

所以我有一个用于连接数据库的辅助类,但现在我希望能够使用同一个类连接到同一代码块中的不同数据库。

助手班级:

<?php
require_once 'config.php'; // Database setting constants [DB_HOST,  DB_NAME, DB_USERNAME, DB_PASSWORD]

class dbHelper {
    private $db;
    private $err;
    function __construct() {
        $dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8';
        try {
            $this->db = new PDO($dsn, DB_USERNAME, DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        } catch (PDOException $e) {
            $response["status"] = "error";
            $response["message"] = 'Connection failed: ' . $e->getMessage();
            $response["data"] = null;
            exit;
        }
    }

    function select($table, $where){
        try{
            $a = array();
            $w = "";
            foreach ($where as $key => $value) {
                $w .= " and " .$key. " like :".$key;
                $a[":".$key] = $value;
            }
            $stmt = $this->db->prepare("select * from ".$table." where 1=1 ". $w);
            $stmt->execute($a);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            if(count($rows)<=0){
                $response["status"] = "warning";
                $response["message"] = "No data found.";
            }else{
                $response["status"] = "success";
                $response["message"] = "Data selected from database";
            }
                $response["data"] = $rows;
        }catch(PDOException $e){
            $response["status"] = "error";
            $response["message"] = 'Select Failed: ' .$e->getMessage();
            $response["data"] = null;
        }
        return $response;
    }
}

所以你可以通过设置常量然后调用函数来调用上面的函数:

dbconfig.php

<?php
     /**
     * Database configuration
 */
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'database1');

?>

page.php文件

<?php
require_once 'dbHelper.php';
$db = new dbHelper();

$rows = $db->select("customers_php",array());
print_r(json_encode($rows,JSON_NUMERIC_CHECK));
?>

我想放弃对config.php文件的需求,并将DB_HOST,DB_NAME等移动到类内部的函数中,并将数据库名称与$ table和$ where info一起传递。

if($db_name == 'database1')
{
    //#----------open database connection --------------------> TESTING
    $db_host = "localhost";
    $db_user = "root";
    $db_password = "";
    $db_name = "database1";
}

if($db_name == 'database2')
{
    //#----------open database connection --------------------> TESTING
    $db_host = "localhost";
    $db_user = "root";
    $db_password = "";
    $db_name = "database2";
}

newpage.php

<?php
require_once 'dbHelper.php';
$db = new dbHelper();

//function select($dbname, $table, $where)......................

$rows = $db->select("database1","customers_php",array());
print_r(json_encode($rows,JSON_NUMERIC_CHECK));
?>

那么,我在哪里/可以把&#34; if($ dbname)&#34;一部分?

1 个答案:

答案 0 :(得分:0)

您可以将if($dbname)部分放入config.php,然后以这种方式修改您的dbHelper课程:

class dbHelper
{
    public function __construct( $db_host, $db_user, $db_password, $db_name )
    {
        (...)
    }
    (...)
}

并以这种方式调用它:

$db = new dbHelper( $db_host, $db_user, $db_password, $db_name );

编辑:

我认为为每个连接维护一个实例可能会更好,但是 - 如果你想在运行中更改它 - 你可以修改你的类:

class dbHelper 
{
    function __construct( $db_host, $db_user, $db_password, $db_name )
    {
        $this->connect( $db_host, $db_user, $db_password, $db_name );
    }

    function dbSelect( $db_host, $db_user, $db_password, $db_name )
    {
        if( $this->db ) $this->db = Null;
        $dsn = 'mysql:host='.$db_host.';dbname='.$db_name.';charset=utf8';
        try {
            $this->db = new PDO($dsn, $db_user, $db_password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
        } catch (PDOException $e) {
            $response["status"] = "error";
            $response["message"] = 'Connection failed: ' . $e->getMessage();
            $response["data"] = null;
            exit;
        }
    }

    (...)

}

然后通过dbHelper->dbSelect()更改数据库连接。