Search code examples
phpinheritancemethodstype-hinting

PHP method argument typehint of class object - can an class inheriting from defined in type proceed?


If I have class Page and SubPage. SubPage inherits from Page. Then I have another class and its method where the method has defined argument type as object class of Page. If I call the method with instance of Page class everything should be fine. But if I call this method with SubPage instead of the Page class instance as defined, what will be the result? Will it proceed or will it drop exception?

Called class and its method:

Class ABC {
public function testMethod(Page $pageInstanceObject){}
}

class Page{
}
class SubPage extends Page{
}

Page and SubPage calls:

$ABC = new ABC();

$page = new Page();
$ABC->testMethod($page);

$subpage = new SubPage();
$ABC->testMethod($subpage); 

Solution

  • Yes the class inheriting can proceed from type hint if the class actually extends - inherits from the class defined in the type hint.