JavaEar 专注于收集分享传播有价值的技术资料

Fatal error: Cannot access empty property - function connect()

When I use this PHP coding, I get the following error:

Fatal error: Cannot access empty property in /connection.php on line 29

class connectionClass

    var $host = '';
    var $user = '';
    var $password = '';
    var $db = '';
    var $con

    function __construct($flag)
        if($flag == "local"):
            $this->host = "localhost";
            $this->user = "root";
        elseif($flag == "remote"):
            $this->host = "";
            $this->user = "root";
            echo "Incorrect connection flag.";

        $this->password = $password;
        $this->db = $db;

    function connect()
        $con = mysql_connect($this->host, $this->user, $this->password) or die(mysql_error());
        mysql_select_db($this->db, $con) or die(mysql_error());


Any suggestions? Thanks in advance.


  1. What is with the alternative syntax in a class? Bad practice -- you are not writing a template. Use curly brackets.

    Most likely your problem is here:

     $this->password = $password;
     $this->db = $db;

    You assign $password to your class variable, but $password is not a parameter in the constructor. So your $this->password is null. Same problem with $this->db.

  2. 参考答案2
  3. Problem is in your '__construct' function.

    Look at the line 23, '$this->db = $db;'. Make sure you define the local variable $db with a value.

    Note: The definition of variable '$password' (line 22) is missing too. Make sure you define that too with a value.