I want to instantiate an object like this:
$foo=new myClass(); $foo->method1()->method2(); How I will set the class for this?
You need to return in this method $this As example:
class A { function first() { //do some stuff return $this; } function second() { //do some stuff return $this; } } $obj = new A(); $obj->first()->second(); There is a pattern "Fluent intarface", some simple example. And check this.
need to return $this, what he needs to return is an object with the method he is chaining. It could be any instance with the right implementations of a method being called in the chain (which also implies the possibility that $this implements the method being called in the chain).I think your code should look something like this:
(Code is not complete it only should give the idea how it could work)
<?php class Database { private $hostname = "localhost"; private $dbName = "dbName"; private $username = "root"; private $password = ""; private $connection; private $queryString = ""; public function __construct($hostname, $dbName, $username, $password) { $this->hostname = $hostname; $this->dbName = $dbName; $this->username = $username; $this->password = $password; try { $this->connection = new PDO("mysql:host=" . $this->hostname . ";dbname=" . $this->dbName . "", $this->username, $this->password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo $e->getMessage(); } } public function Close() { $this->connection = null; } public function Select($select) { $this->queryString .= "SELECT $select"; return $this; } public function From($from) { $this->queryString .= " FROM $from"; return $this; } public function Where($column, $value) { $this->queryString .= " WHERE $column = '$value'"; return $this; } public function execute() { $stmt = $this->connection->prepare($this->queryString); $stmt->execute(); } } $db = new Database("localhost", "dbName", "root", ""); $db->Select("id")->From("xy")->Where("name", "peter")->execute(); ?>
method1()has to return something that has amethod2(). But what is it that you really want to achieve?