August 27, 201214 yr My question (or problem) exists with trying to find if a child class has access to a method of a certain name. I've done some google searching on it, and one solution I've found is simply passing the instance of the child class to the parent but I was wondering if there was a way to check in a more direct manner. <? abstract class ParentClass { protected function __construct( $var=null ) { if ($var == "testing") { // 1. check if child has method "testing" // 2. call "testing" } } } class ChildClass extends ParentClass { public function __construct( $var=null ) { parent::__construct( $var ); } public function testing() { echo "Testing exists"; } } $child = new ChildClass("testing"); Edited August 27, 201214 yr by Siege84
August 27, 201214 yr you can check method_exists and is_callable. Remember that parent methods and members will be available to the child class so you can probably get away with using $this or parent. If you need more advanced checking your can use reflection - http://php.net/manual/en/book.reflection.php
August 27, 201214 yr Author you can check method_exists and is_callable. Remember that parent methods and members will be available to the child class so you can probably get away with using $this or parent. If you need more advanced checking your can use reflection - http://php.net/manua....reflection.php I'm not at all familiar with reflection yet. However, after seeing your post I adjusted my code to the following and it seems to work as intended. Just a small change to the parent constructor: <? abstract class ParentClass { protected function __construct( $var=null ) { if ( method_exists($this, $var) && is_callable( array($this, $var)) ) $this->$var(); } } class ChildClass extends ParentClass { public function __construct( $var=null ) { parent::__construct( $var ); } public function testing() { echo "Testing exists"; } } $one = new ChildClass(); $two = new ChildClass("testing");
August 28, 201214 yr You want the parent class to know if a child class has a certain method? Am I understanding your question correctly?
Create an account or sign in to comment