无法在PHP中连接到BD

时间:2016-08-26 21:02:03

标签: php mysqli

不确定我的php错误在哪里:

class BDConnection{


        private $_bdname;
        private $_root;
        private $_address;

        function __construct(){

            $this->$_address = 'localhost';
            $this->$_bdname = 'Vuelos';
            $this->$_root   = 'root';
        }

        static function link($con){

            $connection = mysqli_connect("$con->_address","$con->_root","","$con->_bdname") or die("Problemas con la conexión");

            return $connection;
        }

        static function close($con){

            mysqli_close($con);

            return;
        }


    }

执行部分:

$connection = new BDConnection();
$conexion= BDConnection::link($connection);

给我的错误:

    Notice: Undefined variable: _address in C:\xampp\htdocs\EjerPHP\PruebaFormularios\BDConnection.php on line 12

    Fatal error: Uncaught Error: Cannot access empty property in C:\xampp\htdocs\EjerPHP\PruebaFormularios\BDConnection.php:12 
Stack trace: #0 C:\xampp\htdocs\EjerPHP\PruebaFormularios\PasajeroVueloconForm.php(31): BDConnection->__construct() #1 {main} thrown in C:\xampp\htdocs\EjerPHP\PruebaFormularios\BDConnection.php on line 12

不确定为什么它没有识别$ _address以及可能出现的错误

2 个答案:

答案 0 :(得分:1)

很多货物崇拜节目:

    function __construct(){

        $this->$_address = 'localhost';
        $this->$_bdname = 'Vuelos';
        $this->$_root   = 'root';
               ^^^^^^
那时

$_root未定义,因此您有效地尝试$this->null = 'root'。所有这些$_都应该只是 _

所有"$con->_address" - 类型变量的使用也是多余的。执行"$var"没有意义,只需使用$var

答案 1 :(得分:0)

<?php 
class BDConnection{
    private $dbname;
    private $username;
    private $host;

    function __construct(Array $credentials){

        $this->host = $credentials['HOST'];
        $this->dbname = $credentials['DB_NAME'];
        $this->username   = $credentials['USERNAME'];
    }

    static function link(BDConnection $connection){

        return mysqli_connect($connection->host,$connection->username,"",$connection->dbname) or die("Problemas con la conexión");
    }

    static function close(BDConnection $con){

        mysqli_close($con);

        return;
    }


}
$credentials = ['HOST'=>'localhost','DB_NAME'=>'songs','USERNAME'=>'root'];
$connection = new BDConnection($credentials);
$conexion= BDConnection::link($connection);