连接到数据库时未定义的变量

时间:2015-03-10 13:53:54

标签: php oop constructor

当我尝试调用user方法时,我不知道为什么hostpasswordconnect()变量未定义

    $app->get('/get', function () use($app){
        $db = new Db_handler;
        $db->connect();
    }
);

这是Db_handler类本身

    <?php
        class Db_handler{
                private $driver;
                private $host;
                private $port;
                private $schema;
                private $username;
                private $password;

                function Db_handler( $config_file = 'connection.ini' ){
                        if(!$connection_data = parse_ini_file($config_file, true)) throw new exception("No se puedo abrr el fichero de configuracion ".$config_file." .");
                        $driver = $connection_data["database"]["driver"];
                        $host = $connection_data["database"]["host"];
                        $port = $connection_data["database"]["port"];
                        $schema = $connection_data["database"]["schema"];
                        $username = $connection_data["database"]["username"];
                        $password = $connection_data["database"]["password"];

                        echo $host;
                        echo $username;
                        echo $password;
                }

                function connect(){
                        $link = mysql_connect($host, $username, $root)
                        or die('No se pudo conectar: ' . mysql_error());
                }

        }
?>

构造函数的回显正确显示变量。

3 个答案:

答案 0 :(得分:1)

在构造函数和connect()方法中,使用$ this作为每个var名称的前缀。

$this->driver = ...
$this->host   = ...

答案 1 :(得分:0)

编辑您的连接功能。改变这一行:

$link = mysql_connect($host, $username, $root)

到此:

$link = mysql_connect($this->host, $this->username, $this->password)

函数connect中使用的变量是未初始化的局部变量。当您使用关键字$ this with pointer - &gt;您将调用已在构造函数中定义的类变量。因此,在构造函数中设置类私有变量也很重要:

$this->driver = $connection_data["database"]["driver"];
$this->host = $connection_data["database"]["host"];
$this->port = $connection_data["database"]["port"];
$this->schema = $connection_data["database"]["schema"];
$this->username = $connection_data["database"]["username"];
$this->password = $connection_data["database"]["password"];

答案 2 :(得分:0)

我认为未定义的变量只是$ root。 你致电mysql_connect($host, $username, $root) 并且$ root未在任何地方声明。