Первый класс наследует PDO
<?php
namespace Modules;
use PDO;
class MyPDO extends PDO
{
public function __construct($dsn, $username = NULL, $password = NULL, $options = [])
{
$default_options = [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$options = array_replace($default_options, $options);
parent::__construct($dsn, $username, $password, $options);
}
public function run($sql, $args = NULL)
{
if (!$args) {
return $this->query($sql);
}
$stmt = $this->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
Второй class User с двумя методами :
<?php
namespace Modules;
class User1
{
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
private $_db;
public function __construct(MyPDO $pdo)
{
$this->_db = $pdo;
}
//Select all
public function findAll()
{
$sql = "SELECT * FROM users";
return $this->_db->run($sql)->fetchAll(\PDO::FETCH_CLASS,__CLASS__);
}
//Find by id
public function findById($id = 0)
{
$sql = "SELECT * FROM users WHERE id =? LIMIT 1";
return $this->_db->run($sql, [$id])->fetchObject(__CLASS__);
}
}
Код вывода :
const DB_DSN = 'mysql:host=localhost;dbname=photo_gallery;charset:utf8';
const DB_USER = "admin";
const DB_PASS = "123qwe";
const DB_OPT = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$abc= new \Modules\MyPDO(DB_DSN,DB_USER,DB_PASS,DB_OPT);
$user = new \Modules\User1($abc);
И вот ниже пишу :
var_dump($user->findById(1));
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Modules\User1::__construct(), 0 passed and exactly 1 expected in
При второй тоже ошибка:
var_dump($user->findAll());
Fatal error: Uncaught ArgumentCountError: Too few arguments to function Modules\User1::__construct(), 0 passed and exactly 1 expected
Хотя если делаю так :
public function findById($id = 0)
{
$sql = "SELECT * FROM users WHERE id =? LIMIT 1";
return $this->_db->run($sql, [$id])->fetchObject();
}
//And then
var_dump($user->findById(1));
//Result
object(stdClass)#5 (5) { ["id"]=> int(1) ["username"]=> string(7) "flaming" ["password"]=> string(6) "123qwe" ["first_name"]=> string(4) "Alex" ["last_name"]=> string(4) "Love" }
Вчера вечер убил на это, так и не понял в чем проблема. И она явно заключается в использовании fetchObject(__CLASS__) и fetchAll(\PDO::FETCH_CLASS, __CLASS__).