Hi everyone !
My question is same as title, I am trying to make a function in class 1 work in another function in class 2.
I tried extends MyFirstClass in second class but didnt work, I tried to include $pdo instance into function I am calling but got error undeffined pdo.
Can some one help me please, Thanks
Here are my classes they are in different files.
Class 1 which is working fine:
class MyFirstClass {
private $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
function runQuery($query, $params) {
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
return $stmt;
}
}
And here is my second class:
require "db.php";
require "MyFirstClass.php";
class MySecondClass {
function getMemberByUsername($username) {
$call_func = new MyFirstClass();
$query = "Select * from users where username = ?";
$result = $call_func->runQuery($query, array($username));
return $result;
}
}
You have a number of problems with your code but in particular,
$call_func = new MyFirstClass();
Is not going to work because the class need your $pdo object to be injected. You really should get yourself a decent IDE which will flag this sort of stuff for you.
Plus, naming thing like MyFirstClass is not really helpful. It’s easier to understand what is happening when you use appropriate names.
So MyFirstClass is actually a DataBase Access Layer (DBAL) class which wraps your pdo object.
class DBAL {
/** @var PDO */
private $pdo;
public function __construct($pdo) {
$this->pdo = $pdo;
}
function runQuery($query, $params) {
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
return $stmt->fetchAll(); // rows of data
}
}
Notice that runQuery was tweaked to provide the actual array results of the query. It makes little sense to return a $stmt object when you are trying to isolate the rest of your code from pdo.
MySecondClass looks like it has some utility methods for accessing the user database information. This is typically called a repository class and needs to have your dbal object injected.
class UserRepository {
/** @var DBAL */
private $dbal;
public function __construct($dbal) {
$this->dbal = $dbal;
}
function getMemberByUsername($username) {
$query = "Select * from users where username = ?";
$users = $this->dbal->runQuery($query, array($username));
return $users[0]; // Add some error checking
}
}
And then we tie it all together:
require_once 'db.php'; // This creates $pdo
$dbal = new DBAL($pdo);
$userRepository = new UserRepository($dbal);
$user = $userRepository->getMemberByUsername('jbiden');
The else is pointless, get rid of it. return basically acts as exit. You should also get in the habit of failing early. You may also want to throw an exception.
Why would a method with the above name return a boolean? Maybe if it was called something like doesMemberForUsernameExist. But get usually implies that the method gets something.