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 Java, a method can return an abstract class or interface type. What will actually be returned is an object that implements that interface, or extends that abstract class.
Yes, we can declare an abstract class with no abstract methods in Java. An abstract class means that hiding the implementation and showing the function definition to the user. An abstract class having both abstract methods and non-abstract methods.
You can never, in no context, change an int from a overridden method into a float in the overriding method. The only special case that is allowed is return type covariance.
Abstract class in Java is similar to interface except that it can contain default method implementation. An abstract class can have an abstract method without body and it can have methods with implementation also. abstract keyword is used to create a abstract class and method.
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 :
/**
* @param string $a blah blah
* @return int The return value blah blah
*/
public function my_method($a);
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 :
class ClassA {
/**
* @param string $a blah blah
* @return ClassB The return value blah blah
*/
public function my_method($a) {
echo 'blah';
}
}
class ClassB {
// ...
}
$a = new ClassA();
$returned = $a->my_method(10);
if (!$returned instanceof ClassB) {
throw new Exception("Should have returned an instance of ClassB !");
}
Here, as the method doesn't return an instance of ClassB
, the exception will be thrown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With