Ali Hesari Ali Hesari - 3 months ago 10
MySQL Question

Mysql - Parse error (syntax error) in my code

When I use:

$mysqli = new mysqli('localhost', 'root', '', 'cms');


in my class, As a result display Error:

Parse error: syntax error, unexpected '$mysqli' (T_VARIABLE), expecting function (T_FUNCTION) in D:\xamppp\htdocs\cms\includes\td-class-db.php on line 12


And when use
$mysqli = new mysqli('localhost', 'root', '', 'cms');
outsilde the class no display any error!

My class:

class Connect_db{
$mysqli = new mysqli('localhost', 'root', '', 'cms');
}


why?

Answer

You can't instantiate classes when creating member variables in a class. You have to do this in the constructor or a method:

class Connect_db{
    private $mysqli;

    public function __constructor() {
        $this->mysqli = new mysqli('localhost', 'root', '', 'cms');
    }
}
Comments