我想在PHP OOP中的另一个方法中使用一个方法
我想实例化一个对象,如下所示:我想在PHP OOP中的另一个方法中使用一个方法,php,oop,Php,Oop,我想实例化一个对象,如下所示: $foo=new myClass(); $foo->method1()->method2(); 我将如何为此设置类?您需要在此方法中返回$this 例如: class A { function first() { //do some stuff return $this; } function second() { //do some stuff
$foo=new myClass();
$foo->method1()->method2();
我将如何为此设置类?您需要在此方法中返回$this 例如:
class A
{
function first()
{
//do some stuff
return $this;
}
function second()
{
//do some stuff
return $this;
}
}
$obj = new A();
$obj->first()->second();
有一个模式,一些简单的例子。然后检查。我认为您的代码应该如下所示:
$foo=new myClass();
$foo->method1()->method2();
代码并不完整,它只应该给出如何工作的想法
<?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必须返回包含method2的内容。但你真正想要实现的是什么呢?它被称为方法链接或fluent接口。我想创建一个数据库类。我想写这样的代码$db->select*/custom->fromtable;他不需要返回$this,他需要返回的是一个带有链接方法的对象。它可以是链中调用的方法的正确实现的任何实例,这也意味着$this实现链中调用的方法的可能性。这是一个非常有用的示例。谢谢您: