2

I want to instantiate an object like this:

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

How I will set the class for this?

Biffen
  • 6,249
  • 6
  • 28
  • 36
Mahmoodur
  • 23
  • 1
  • 8

2 Answers2

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.

Community
  • 1
  • 1
sergio
  • 5,210
  • 7
  • 24
  • 46
  • He doesn't `need` to return `$this`, what he `need`s 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). – dbf Jan 10 '15 at 21:23
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();

?>
Rizier123
  • 58,877
  • 16
  • 101
  • 156