Reputation: 23
I want to instantiate an object like this:
$foo=new myClass();
$foo->method1()->method2();
How I will set the class for this?
Upvotes: 2
Views: 143
Reputation: 59691
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();
?>
Upvotes: 3
Reputation: 5260
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.
Upvotes: 3