oop - PHP singleton pattern -


hello there want learn singleton pattern in php, have 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 * $table';     }      public function result()     {         echo $this->query;      }  }   $db = database::getinstance(); 

and , posible call result() method , print value set query() "select * $table" using singleton?

i want code in like:

$db->query('user_tb')->result();  //output select * user_tb; 

update:

to able call like:

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

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

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

now can call : $db->query('user_tb')->result();

working example

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

first modify in query() method:

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

to:

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

since inside single quotes, variables not parsed.

and define $query @ class level this:

class database {   private static $instance;   private $query = '';   // more code } 

and can run it:

$db = database::getinstance(); // class instance $db->query('user_tb'); // set $query var $db->result(); // $query var 

result:

select * user_tb 

working example


Comments

Popular posts from this blog

django - How can I change user group without delete record -

java - Need to add SOAP security token -

java - EclipseLink JPA Object is not a known entity type -