tags:

views:

74

answers:

3

Why is it possible to create an interface without specifying a return type? Why doesn't this make this interface unusable?

This makes it more Clear:

Interface run
{
    public function getInteger();
}

class MyString implements run
{    
    public function myNumber()
    {

    }

    public function getInteger()
    {  
        return "Not a number";
    }    
}

In Java every Interface has a return type like Integer, String or Void

I know that PHP is unfortunately a loosely typed Language but isn't there a Solution to that Problem?

Is it possible to define an Interface with a return type like Integer?

+4  A: 

No, there is not. You said the reason yourself: PHP is loosly typed.
You can have hints in PHPDoc, or check the type in the function you use the interface's functions and throw an InvalidArgumentException if you get something else but an integer.

Maerlyn
+2  A: 

PHP currently does not support type hinting for function/method arguments or return values. Adding them is currently up for discussion in this PHP RFC (which lists the options).

The current accepted practice is to use phpdoc comments to indicate the "contract" is present.

/** 
 * Does something.
 * @return int
 **/
public function getInteger() { return 1; }

If the code violates the "contract," I suggest finding the original coder and having them fix it and/or filing a bug and/or fixing it yourself if it's in your own codebase.

Charles
A: 

In and of itself what you want is not possible...

In short: If you really need to enforce return types in your code contracts, use a statically typed language.

But thanks to the magic of __get, __set, __call and friends, you could define a base class that enforces type safety (I wouldn't recommend this for anything other than research/playtime) but that will still not help you define type safe interfaces.

Kris