I want to use a method inside another method in PHP OOP
2 answers
You need to return to this method $this
As an 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 Free Internal File template , a simple example. And check this one .
+4
source to share
I think your code should look something like this:
(The code is not complete, it should only give an idea of how it might 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();
?>
+4
source to share