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
?
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.
It should be noted that this is now possible with PHP7 (only Beta1 has been released at time of writing)
It is possible with the following syntax:
Type hinting for function/method arguments or return values is only supported at PHP7.0 or later
Check the details here: http://php.net/manual/en/migration70.new-features.php
If you are using PHP5 so the current accepted practice is to use phpdoc comments to indicate the "contract" is present.
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.
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.