-1

I have been experimenting with persistent data from a class construct, I am trying to make a persistent connection through my public __construct, so I can use my database connection information throughout my class. My code is as followed:

class Inbox {
   # private $Database;
    public function __construct() {
        $this->$Database = new mysqli ('localhost','root','xxx','test');
    }
    public static function TestConnect (){
        if (self::Database){
            echo "Success When Connecting To Database";
        }else{
            echo "Problems When Connecting To Database";
        }
    }
    public static function TestSelect(){
        $Select = $this->Database->prepare("SELECT * FROM test");
        $Select->execute();
        $Select->bind_result($Test_ID, $Test_UName);
        $Select->fetch();

        print_r($Select);
    }
}

$Foo = new Inbox();
$Foo->TestSelect();

Now. When running

I am presented with the following errors:

Notice: Undefined variable: Database in C:\xampp\htdocs\InboxFeature\Api\Class.php on line 15

Fatal error: Cannot access empty property in C:\xampp\htdocs\InboxFeature\Api\Class.php on line 15


I change my lines to:

$Select = self::Database->prepare("SELECT * FROM test");

and uncomment: private $Database;

I get presented with the error:

Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in C:\xampp\htdocs\InboxFeature\Api\Class.php on line 25

So my overall question, is where exactly have I gone wrong, I have looked at examples shown on Stackoverflow with using the __construct() method. I can't see where it's gone wrong for me.


Using the Answer provided. I appended the following changes:

 private static $Database;
    public function __construct() {
        self::$Database = new mysqli ('localhost','root','xxx','test');
    }
    public static function TestSelect(){
        $Select = self::$Database->prepare("SELECT * FROM test");
        $Select->execute();
        $Select->bind_result($Test_ID, $Test_UName);
        $Select->fetch();

        echo $Test_ID;
    }

This has successfully worked. Thank you for the quick response

4

1 回答 1

0

You have the syntax reversed.

If you declare the property as private $database; then you would access it using $this->database, not $this->$database.

If you instead declare it as a static property (private static $database) then it would be self::$database, not self::database.

Either way, you should make sure the property is declared at the top of the class; in your example you have private $database commented out.

于 2013-03-31T02:05:58.800 回答