PHP - 从另一个类调用数据库类

时间:2017-08-26 16:47:24

标签: php

我最近在代码中遇到错误:

PHP Parse error:  syntax error, unexpected '$connection' (T_VARIABLE), expecting function (T_FUNCTION) in

根据我的Google搜索,问题不是在构建函数之前设置public / private / protected,或者不在构造函数中创建数据库连接。

数据库连接类代码:

 class databaseConnection {


    //Database information
    protected $mysqliUser = "";
    protected $mysqliHost = "localhost";
    protected $mysqlipass = "";
    protected $mysqlidbname = "";
    public $con;


    public function __construct() {
        $this->con = new mysqli($this->mysqliHost,$this->mysqliUser,$this-
        >mysqlipass,$this->mysqlidbname); 

    }

}

收到错误的类代码片段:

private $conn;
    $conn = new databaseConnection;

非常感谢任何帮助我指明正确方向的帮助。

2 个答案:

答案 0 :(得分:1)

  私有声明之上的

只是类创建类   了createSession

在这种情况下,您的$conn = new databaseConnection;要么可见,要么应该在方法中。很难说没有看到你所有的课程和奇怪的缩进。

所以把它放在它所属的方法中(也许是构造函数?)或者将它设置为private,protected或public - 无论它是用于哪个。

答案 1 :(得分:0)

检查一下。

它真的有用..

  

<强> connect.php

class DBConnect {
    private static $connection;
    private static $host = "localhost";
    private static $user = "root";
    private static $pwd = "";
    private static $dbname = "yourDBName";

    public static function connect() {
        $host = self::$host;
        $user = self::$user;
        $pwd = self::$pwd;
        $dbname = self::$dbname;

        self::$connection = new mysqli($host, $user, $pwd, $dbname) or die('Error connecting..');
        return self::$connection;
    }
}
  

<强> myclass.php

require_once('connect.php');

class MyClass {
    private $connObj;

    public function __construct() {     
        $this->connObj = DBConnect::connect();
    }

    public function select() {
        $conn = $this->connObj;
        $sql = "SELECT * FROM table_name";

        $query = $conn->query($sql);
        $res = $query->fetch_assoc();
        // your code..
    }
}

$obj = new MyClass();
$obj->select();

希望,此代码段适用于您。 :):)