PHP Dependency injection and extending from an umbrella class

I have a database class that has a series of functions in it, and I was advised the best thing to do to access those functions from within another class is dependency injection. What I want to do is have one main class that has the database dependency "injected" into it and then other classes extend off of this class, such as Users, Posts, Pages etc.

This is the main class that has the database dependency injected into it.

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);

And then this is the Users class I'm trying to extend off of it.

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

    }

}

But whenever trying to call the view function for the User class, I'm getting this error Fatal error: Using $this when not in object context. This error is in regards to trying to call $this->database in the Users class. I've tried initializing a new user class and passing the database to it instead, but to no avail.


When you use call_user_func_array and you pass it a callable that is composed of a string name for the class and a string name for the method on the class it does a static call: Class::method() . You need to first define an instance and then pass the instance as the first part of the callable as demonstrated below:

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));
链接地址: http://www.djcxy.com/p/82282.html

上一篇: 程序仅在发布版本时崩溃

下一篇: PHP依赖注入并从伞班延伸