Answer the question
In order to leave comments, you need to log in
What if you need to call the parent constructor with dependencies?
Suppose there is a handler, and every class of a certain type needs it (all subtypes also need this handler).
<?php
interface SomeHandlerInterface {
public function checkParam( string $userName ) : string;
}
class SomeHandler implements SomeHandlerInterface{
/**
* @param string $userName
* @return string
* The method does something with the user name
*/
public function checkParam( string $userName ) : string {
return $userName;
}
}
class ParentClass {
/**
* @var SomeHandler
*/
protected $someHandler;
public function __construct(SomeHandlerInterface $someHandler) {
$this->someHandler = $someHandler;
}
}
class ChildClass extends ParentClass{
public function __construct() {
parent::__construct( new SomeHandler() );
}
}
Answer the question
In order to leave comments, you need to log in
class ChildClass extends ParentClass {
public function __construct(
SomeHandlerInterface $someHandler,
AnotherHandlerInterface $anotherHandler
) {
parent::__construct($someHandler);
$this->anotherHandler = $anotherHandler;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question