homelessDevOps
homelessDevOps

Reputation: 20726

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?

Upvotes: 0

Views: 840

Answers (2)

outis
outis

Reputation: 77400

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.

Upvotes: 1

Amy B
Amy B

Reputation: 17977

"something like" WHAT exactly?

Anyway, your syntax is totally wrong...

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

Upvotes: 0

Related Questions