Afs35mm
Afs35mm

Reputation: 649

Why can't I set a class' properties in it's parent's constructor? (php)

I've been following the no-framework php tutorial (related chapter here: https://github.com/PatrickLouys/no-framework-tutorial/blob/master/07-inversion-of-control.md). And while extending it, as an abbreviated example, everything works fine when I'm instantiating the various properties of the class:

use Http\Request;

class User extends Super_user
{
    private $request; 

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }
}

However when I try and set the request in the parent I seem to get the error: Argument 1 passed to Namespace\Controllers\Super_user::__construct() must be an instance of Namespace\Template\Request, none given, called in...

class User extends Super_user
{

    public function __construct()
    {
        parent::__construct();
    }
}

...

use Http\Request;

class Super_user
{
    public function __construct()
    {
        $this->request = $request;
    }

}

Any help would be greatly appreciated from someone who is fairly new to PHP...

Upvotes: 0

Views: 378

Answers (1)

Klaus
Klaus

Reputation: 461

As Super_user class requires an Request object in its constructor. You should declare your User's constructor method like this

public function __construct(Request $request)
{
    parent::__construct($request);  // Pass $request object to Parent's method
    $this->request = $request;
}

Upvotes: 1

Related Questions