4

As far as I know, constructors don't return values. The problem I'm facing below is, I have to repeat calling check_error() in every method of child class to see if parent $error array has any errors in it or not.

Is there any chance changing my code to remove replications to make it more user friendly and maintainable?

Thanks

class RestfulRequest extends Restful
{
  public function __construct()
  {
     parent::__construct();

     if (is_array($this->error))
     {
        return 'Error found';
     }
  }
..
..
..
}

I know the code above is not possible but I'm just adding to show you what I needed in first place. No repetition, just one check in every initiations.

abstract class Restful
{
  public $error = array('error1', 'error2');
  abstract public function check_error();
  abstract public function method_one();
  abstract public function method_two();
}

class RestfulRequest extends Restful
{
  public function __construct()
  {
     parent::__construct();
  }

  public function check_error()
  {
     return (is_array($this->error)) ? false : true;
  }

  public function method_one()
  {
     if ($this->check_error() === false)
     {
        return 'Error found';
     }

     return 'No error';
  }

  public function method_two()
  {
     if ($this->check_error() === false)
     {
        return 'Error found';
     }

     return 'No error';
  }
}

$obj_restful = new RestfulRequest();
echo $obj_restful->method_one();
echo $obj_restful->method_two();
BentCoder
  • 12,257
  • 22
  • 93
  • 165

1 Answers1

2

Constructors can't return values, but they can throw exceptions.

Class RestfulRequest extends Restful
{
  public function __construct()
  {
     parent::__construct();

     if (is_array($this->error))
     {
        throw new Exception('Error found.');
     }
  }
..
..
..
}
BenM
  • 52,573
  • 26
  • 113
  • 168
  • A question: Would `$obj_restful->method_one();` and `$obj_restful->method_two();` be ignored (canceled) immediately if error found in Constructor? – BentCoder Feb 15 '13 at 14:35
  • That largely depends how you handle the exception. – BenM Feb 15 '13 at 14:40