扩展抽象类时出现意外结果

I'm trying to print an error on purpose 'There is an error' but getting 'Success' message instead?

Any idea why?

Thanks

abstract class Restful
{
  public $error = array();

  public function __construct()
  {
     //Doing something here
     //....
     //....
     $this->validate_params();
  }

  public function validate_params()
  {
     $this->error[] = 'test error';
  }
}

class RestfulRequest extends Restful
{
  public function __construct()
  {
     if (count($this->error) > 0)
     {
        exit('There is an error');
     }

     echo 'Success';
  }
}

new RestfulRequest();

You forgot to call the parent constructor:

class RestfulRequest extends Restful
{
  public function __construct()
  {
     parent::__construct(); // <-- added
     if (count($this->error) > 0)
     {
        exit('There is an error');
     }

With PHP's class extending mechanism, the when you override a method, only the overridden method is called; the method from the parent class is not called unless you call it explicitly.

Therefore, in your example, the __construct() method from the base class is never called.

In order to do what you want, you need to make the RestfulRequest::__construct() method call it's parent method explicitly, like so:

public function __construct()
  {
     parent::__construct();    //add this line!
     if (count($this->error) > 0)
     {
        exit('There is an error');
     }

     echo 'Success';
  }

Hope that helps.