我想在PHP OOP中的另一个方法中使用一个方法

时间:2015-01-10 11:17:39

标签: php oop

我想实例化一个这样的对象:

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

我将如何为此设置课程?

2 个答案:

答案 0 :(得分:4)

您需要使用此方法返回$this 例如:

class A
{
     function first()
     {
         //do some stuff
          return $this;
     }
     function second()
     {
         //do some stuff
          return $this;
     }
}

$obj = new A();
$obj->first()->second();

有一种模式" Fluent intarface",一些简单的例子。并查看this

答案 1 :(得分:4)

我认为你的代码应该是这样的:

(代码不完整,它只能说明它是如何工作的)

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

?>