Possible to use a function inside of a different c

2019-09-21 18:34发布

问题:

EDIT:::
So I have classes that I would like to work together. My first two establish a connection to the database:


dbconn.php

<?php

class dbconn {
    protected $dbname;
    protected $dbuser;
    protected $dbpassword;
    protected $dbhost;
    protected $connection;

    public function __construct($dbhost, $dbname, $dbuser, $dbpass) 
    {
        $this->dbname = $dbname;
        $this->dbhost = $dbhost;
        $this->dbuser = $dbuser;
        $this->dbpass = $dbpass;
        $this->connect();
    }

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

    protected function connect()
    {
        $this->connection = new PDO("mysql:host={$this->dbhost};dbname={$this->dbname}", $this->dbuser, $this->dbpass);
    }
}
?>


dblogin.php

<?php

$db = new DBconn('localhost','phpproject','carl','pdt1848?')

?>

My other class is trying to edit items from the database. I tried to link the db connection classes throught the __construct of this class, I'm just going about this all wrong apparently.
editbeers.php

<?php

class BeerEditor
{
    protected $dbconn;

    function __construct($dbconn){
        $this->dbconn = $dbconn;
    }

    function addBeer(Beer $beerObj){
        //making connection to db here
        $conn = $this->dbconn->getConnection();

        $stmt = $conn->prepare("INSERT INTO beers (beer_name, beer_type, beer_abv, beer_rating) VALUES (:beer_name, :beer_type, :beer_abv, :beer_rating)");

        $stmt->bindParam(':beer_name', $beerObj->getBeerName());
        $stmt->bindParam(':beer_type', $beerObj->getBeerType());
        $stmt->bindParam(':beer_abv', $beerObj->getBeerABV());
        $stmt->bindParam(':beer_rating', $beerObj->getBeerRating());

        $result = $stmt->execute();

        if($result === false){
            var_dump($conn->errorCode());
        }

        return $result;
    }

    function listBeers(){

        $conn = $this->dbconn->getConnection();
        $result = $conn->query('SELECT * FROM beers');

        $result->setFetchMode(PDO::FETCH_CLASS|PDO::FETCH_PROPS_LATE, 'beers');
        $beers = $result->fetchAll();

        return $beers;
    }


}
?>

回答1:

  1. In the second file you've quoted you never actually create $dbconn. If you think it should be created somewhere within /home/carlton/public_html/PHPproject/allincludes.php then you should probably double-check that.

  2. Your constructor could check to see if the information passed to it is somehow valid before allowing it to be stored.



回答2:

perhaps the $dbconn var is defined somewhere in your required file. Try

var_dump($dbconn);

after the require and see if it is the object you expect.



回答3:

Because $dbconn is undefined and not an database connection object you are not able to call the method getConnection().

When creating BeerEditor you need to pass in a database connection object.

$BeerEditor= new BeerEditor($dbconn);