thelem
thelem

Reputation: 2773

Ensuring all exceptions are considered when using PHP

I've used exceptions in Java and like the way it won't let you call a method unless you catch or throw the exceptions that it might throw.

I'm looking for something similar in PHP. I realise PHP is more dynamic than Java, and doesn't even let you define the exceptions that it throws, but what is the closest I can get?

We document our methods using PHP Doc, so something that triggered an E_WARNING if you called a method without the correct try/catch block, or threw an exception without the correct @thows comment, would be perfect.

Upvotes: 4

Views: 236

Answers (4)

Christophe Eblé
Christophe Eblé

Reputation: 8161

I think you can simply reproduce this behavior in PHP using exception handlers and reflection.

class YourException extends Exception {
  public function __toString() {
    return __CLASS__;
  }
}

class MyObject {
    public function __construct(){}
    /**
    * @throws MyException
    */
    public function myMethod() {
        return 'foo';
    }
}

try {
    $o = new MyObject();
    $o->myMethod();
} 
catch(YourException $e) {
    $method = new ReflectionMethod('MyObject', 'myMethod');
    $method->getDocComment();

    $throws = // Get the @throws comment (foreach, regexp, whatever);
    if($e === $throws) {
        // do something
    }
}

Setting your own exception handler.

Grab and analyse the comments with Reflection mechanism (see getDocComment)

Upvotes: 1

Kornel
Kornel

Reputation: 100090

There's no way to do it in PHP itself. You will have to parse PHP and figure it out yourself. Try writing phc plugin for this.

Upvotes: 2

zombat
zombat

Reputation: 94147

I'm not sure that you can accomplish your stated goal. The PHP environment doesn't analyze what a function might or might not do, which would generally be a compile-time operation for other languages (I would think). I don't think you can even find that sort of thing via Reflection.

You are wrong however when you say that you can't define the exceptions that get thrown, as the Exception base class is fully extendable. PHP doesn't throw any exceptions by default though, it triggers errors. There is a fundamental difference between triggered errors and Exceptions, the latter being a user-land construct for the most part.

This isn't your question, but I'd put out a suggestion that if you wanted to move to a fully Exception-oriented environment, you could write your own error handler using set_error_handler() and manage the PHP triggered errors, and have it throw out an Exception.

Upvotes: 1

chaos
chaos

Reputation: 124277

I don't think you can reasonably get very close at all, because the language core provides just nothing whatsoever for you to work with. At best, you'd wind up creating some kind of entirely user-space funcall/exception validation mechanism that would have an absolutely horrific impact on performance.

Upvotes: 1

Related Questions