PHP依赖项注入和从伞类扩展
我有一个数据库类,其中包含一系列函数,有人建议我从另一个类中访问这些函数最好的方法是依赖注入。我想做的是让一个主类将数据库依赖关系“注入”到其中,然后其他类扩展到这个类之外,比如用户、帖子、页面等 这是将数据库依赖项注入其中的主类PHP依赖项注入和从伞类扩展,php,class,dependency-injection,Php,Class,Dependency Injection,我有一个数据库类,其中包含一系列函数,有人建议我从另一个类中访问这些函数最好的方法是依赖注入。我想做的是让一个主类将数据库依赖关系“注入”到其中,然后其他类扩展到这个类之外,比如用户、帖子、页面等 这是将数据库依赖项注入其中的主类 class Main { protected $database; public function __construct(Database $db) { $this->database = $db; } }
class Main {
protected $database;
public function __construct(Database $db)
{
$this->database = $db;
}
}
$database = new Database($database_host,$database_user,$database_password,$database_name);
$init = new Main($database);
然后这就是我试图扩展的Users类
class Users extends Main {
public function login() {
System::redirect('login.php');
}
public function view($username) {
$user = $this->database->findFirst('Users', 'username', $username);
if($user) {
print_r($user);
} else {
echo "User not found!";
}
}
}
但无论何时尝试调用User类的view函数,我都会遇到一个致命错误:在不在对象上下文中时使用$this。此错误与试图在Users类中调用$This->数据库有关。我尝试初始化一个新的用户类,并将数据库传递给它,但没有效果。当您使用
call\u user\u func\u array
并向它传递一个可调用对象,该对象由类的字符串名和类上方法的字符串名组成,它会执行静态调用:class::method()
。您需要首先定义一个实例,然后将该实例作为可调用函数的第一部分传递,如下所示:
class Test
{
function testMethod($param)
{
var_dump(get_class($this));
}
}
// This call fails as it will try and call the method statically
// Below is the akin of Test::testMethod()
// 'this' is not defined when calling a method statically
// call_user_func_array(array('Test', 'testMethod'), array(1));
// Calling with an instantiated instance is akin to $test->testMethod() thus 'this' will refer to your instnace
$test = new Test();
call_user_func_array(array($test, 'testMethod'), array(1));
你能粘贴一个实例化一个新的
用户
实例的代码示例,以及你对视图
方法的调用吗?基本上,我已经设置了一个路由器,在Users类中调用view方法并传递用户名。在路由器中,这是通过调用_user_func_数组(数组(NAMESPACE.$class$function)、数组_值($params))完成的;