简体   繁体   中英

Check from Constructor if function in child class exists?

is it possible to do something like this in PHP 5.2.1?

abstract class Test
{
  public function __construct()
  {
     if (function_exists('init')):
        $this->init();
  }
}

If i try this, the function on the subclass is not called?

You can use method_exists to see if an object has a method with a given name. However, this doesn't let you test what arguments the method takes. Since you're defining an abstract class, simply make the desired method an abstract method.

abstract class Test {
    public function __construct() {
        $this->init();
    }
    abstract protected function init();
}

Just be careful you don't call init more than once, and child classes invoke their parents' constructors.

"something like" WHAT exactly?

Anyway, your syntax is totally wrong...

  public function __construct()
  {
     if (function_exists('init')
     {
        $this->init();
     }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM