Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force a method of an abstract class to return something?

Tags:

php

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?

like image 241
openfrog Avatar asked Dec 27 '09 10:12

openfrog


People also ask

Can a method return an abstract class?

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.

Can you have non-abstract methods in an 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.

Can you change return type of abstract method?

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.

Can abstract classes have implemented methods?

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.


1 Answers

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.

like image 66
Pascal MARTIN Avatar answered Nov 01 '22 22:11

Pascal MARTIN