samdunne
samdunne

Reputation: 316

PHP PDO custom class returning an object and not what it should

So I made a database class to handle all of my database requests. Everything goes through the constructor and it should return values.

The class is so

<?php

class Database {

    /**
     * This array holds all of the configuration settings for the database
     * @var array
     */
    private $config = array(
        'username'  =>  '',
        'password'  =>  '',
        'host'      =>  '',
        'database'  =>  ''
    );

    /**
     * Holds the parameters passed to the class
     * @var mixed
     */
    private $parameters;

    /**
     * Database Handler
     * @var [type]
     */
    private $DBH;

    /**
     * Class constructor
     * @param [type] $action     [description]
     * @param [type] $parameters [description]
     */
    public function __construct($action, $parameters){
        $this->parameters = $parameters;

        $this->DBH = new PDO("mysql:host=".$this->config['host'].";dbname=".$this->config['database'], $this->config['username'], $this->config['password']); 

        return $this->$action();
    }


    private function query(){
        $STH = $this->DBH->prepare($this->parameters);
        $STH->execute();
        $result = $STH->fetchColumn();
        echo "<br><br>RESULT:".$result."<br><br><br>";
        echo "<br><br>RESULT:".empty($result)."<br><br><br>";

        return (empty($result)) ? FALSE : TRUE;
    }
} 

I removed everything bar the function giving issues. It is meant to return true or false. Instead the return value when I call $result = new Database('query', $query); is an object with a ton of data

Any idea what I have done wrong?

Upvotes: 1

Views: 1230

Answers (2)

vstm
vstm

Reputation: 12537

PHP ignores what you return in __construct. If you create a new object with new then the new object is returned and not what the return in __construct says.

To achieve what you want you have to create a new function which executes the action for you outside of the constructor - like that:

class Database {
    // your code...

    public function __construct($parameters) {
        $this->parameters = $parameters;

        $this->DBH = new PDO("mysql:host=".$this->config['host'].
            ";dbname=".$this->config['database'],
            $this->config['username'],
            $this->config['password']); 
    }

    public function perform($action) {
        return $this->$action();
    }

    // rest of your code...
}

// usage:
$db = new Database($query);
$result = $db->perform('query'); // result should be a boolean.

Upvotes: 2

oxygen
oxygen

Reputation: 6049

__construct is suposed to return the newly created object. This behaviour cannot be overriden. See usage.

Btw, this is the behaviour for most OOP languages when the new operator is involved.

Upvotes: 1

Related Questions