2014-02-21 9 views
0

我有一個數據庫類,它有一系列的功能,我建議從另一個類訪問這些功能的最好的事情是依賴注入。我想要做的就是讓一個主類將數據庫依賴項「注入」到其中,然後其他類從這個類中擴展出來,例如Users,Posts,Pages等。PHP依賴注入和從傘類延伸

這是主類數據庫依賴注入到它。

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!"; 
     } 

    } 

} 

但是,試圖呼籲用戶類視圖功能時,我得到這個錯誤致命錯誤:使用$這個時候不是在對象上下文。這個錯誤是關於試圖在Users類中調用$ this->數據庫的。我嘗試初始化一個新的用戶類,並將數據庫傳遞給它,但無濟於事。

+0

您可以粘貼實例化一個新的'Users'實例的代碼示例,以及您的調用'view'方法? –

+0

基本上,我建立了一個路由器,在用戶類中調用view方法並傳遞用戶名。在路由器中,這是通過call_user_func_array(array(__ NAMESPACE__。$ class,$ function),array_values($ params))完成的; – ablshd

回答

0

當你使用call_user_func_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));