2

I want to instantiate an object like this:

$foo=new myClass(); $foo->method1()->method2(); 

How I will set the class for this?

3
  • 4
    method1() has to return something that has a method2(). But what is it that you really want to achieve? Commented Jan 10, 2015 at 11:19
  • It's called "method chaining" or "fluent interface" Commented Jan 10, 2015 at 11:21
  • I want to make a database class. I want to write codes like this $db->select("*/custom")->from("table"); Commented Jan 10, 2015 at 11:22

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

He doesn't 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).
3

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(); ?> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.