mercredi 29 novembre 2017

Using PHP DBC Class in other files [duplicate]

This question already has an answer here:

Coming from Java I am very confused how the PHP class system works. I have a DBC class and a User class. Both I have to use in a third PHP file (signup.inc.php), but this error occurs: Uncaught Error: Call to undefined method DBC::prepare() in User.php DBC::prepare().

So User.php doesn't know that $this->dbc is a PDO object? I tried to google something similar but still don't get how the class/inheritance system works. Does anyone have a tip or tips for improvement?

DBC.php (db connection with singleton):

class DBC {

private $connection;
public static $_instance;
private $dbServer = "...";
private $dbUsername = "...";
private $dbPassword = "...";
private $dbName = "...";

public static function getInstance() {
    if(!self::$_instance) {
        self::$_instance = new self();

        return self::$_instance;

    } else {
        return self::$_instance;

    }
}

private function __construct() {

    try {

        $this->connection = new PDO("mysql:host=".$this->dbServer.";dbname=".$this->dbName,
        $this->dbUsername,
        $this->dbPassword,
        [
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
        ]);

        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        self::$_instance = $this->connection;

doesn't show the rest of this file in one piece ...

} catch (PDOException $error) {
            #...
        }

    }

    private function getConnection() {
        return $this->connection;
    }

}

User.php:

include_once 'DBC.php';

    class User {

        protected $email;
        protected $...;
        protected $...;
        protected $...;
        protected $...;
        protected $...;

        public function __construct($dbc) {
            $this->dbc = DBC::getInstance();
        }

    function findByEmail ($email) {

            $statement = $this->dbc->prepare("SELECT * FROM user WHERE user_email = :user_email");
            $statement->bindParam(":user_email", $email);
            $statement->execute();

            if ($statement->rowCount() > 0) {

                return false;

            } else {

                return $this->createUserFromDB($statement);
            }

        }

And the call in signup.inc.php:

 require_once 'DBC.php';
    require_once 'User.php';

        $dbc = DBC::getInstance();
        $user = new User($dbc);

Aucun commentaire:

Enregistrer un commentaire