-2

Hello there i want to learn a singleton pattern in php, i have a class:

class Database
{
    private static $instance;

    private function __construct() 
    { 
    }

    public static function getInstance()
    {
        if (!self::$instance)
        {
            self::$instance= new Database();
        }

        return self::$instance;
    }

    public function query($table)
    {
         $this->query = 'select * from $table';
    }

    public function result()
    {
        echo $this->query;

    }

}


$db = Database::getInstance();

and now , is it posible to call the result() method and print the value set by the query() which is "select * from $table" using a singleton?

i want my code in something like:

$db->query('user_tb')->result();

//output
select * from user_tb;
Anthony Rutledge
  • 4,817
  • 31
  • 40
avien
  • 167
  • 5
  • 14

2 Answers2

4

Update:

To be able to call it like:

$db->query('user_tb')->result();

You need to put return $this; in method you want to chain, in this case your query method:

public function query($table)
{
     $this->query = "select * from $table";
     return $this;
}

Now you can call it like : $db->query('user_tb')->result();

Working Example

-------------------------------------------------------------------------------------------

First modify in your query() method:

$this->query = 'select * from $table';

To:

$this->query = 'select * from ' . $table;

since inside single quotes, variables are not parsed.

And then define $query at class level like this:

class Database {
  private static $Instance;
  private $query = '';
  // your more code
}

And then you can run this to get it:

$db = Database::getInstance(); // get class instance
$db->query('user_tb'); // set $query var
$db->result(); // get $query var

Result:

select * from user_tb

Working Example

Sarfraz
  • 355,543
  • 70
  • 511
  • 562
  • yes thanks, i did that approach actually but for some reason i want to do a series of coding style like i stated, $db->query('user_tb')->result(); //output select * from user_tb; – avien Jun 11 '12 at 07:29
  • working example links are not working. please update it – Neocortex Jan 29 '15 at 13:45
-1

To use method chaining, make sure all functions you want to chain return $this.

Then you can do DB::getInstance()->query()->result();.=

So query at least needs to return $this.

Also, you forgo any error handling by return parameter, so generally if you use method chaining you need to use exception handling to deal with errors.

As in, you can't do

if(!$db->query) {
    error_log('bleh');
}
j0k
  • 21,914
  • 28
  • 75
  • 84
Didier
  • 126
  • 1
  • 6
  • is there any way to return the instance automatically without returning $this inside each method? – avien Jun 11 '12 at 07:45