I have defined an abstract class and a method which is supposed to return the name of a template file. The user subclasses this abstract class and implements that method to return the template file name. But the problem is, that there happens no warning or whatever if the user just does not return anything.
How could I make this sure? The code that calls this method belongs to the framework, so I could do some fancy stuff with settype($returnVal, 'string') maybe, if that helps? Are there better solutions?
In PHP, you cannot “force” a method to return anything — and it’s not possible, even with abstract classes/methods, nor interfaces.
The best you can do is indicate that the implementation should return something, using a comment — but you cannot force people to do so :
Of course, if you are calling this method (the implementation) from your framework, you can check what has been returned, and throw an Exception if it doesn’t correspond to what you expected…
And here is a quick example of how this could be implemented :
Here, as the method doesn’t return an instance of
ClassB, the exception will be thrown.