Why is it possible to have an interface without a

2020-02-10 14:47发布

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?

标签: php oop
4条回答
Juvenile、少年°
2楼-- · 2020-02-10 15:06

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.

查看更多
【Aperson】
3楼-- · 2020-02-10 15:07

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:

interface Run
{
    public function getInteger(): int;
}

class MyString implements Run
{    
    public function myNumber()
    {

    }

    public function getInteger()
    {  
        return "Not a number";
        // Throws a fatal "Catchable fatal error: Return value of getInteger() must be of the type integer, string returned in %s on line %d"
    }    
}
查看更多
男人必须洒脱
4楼-- · 2020-02-10 15:09

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.

/** 
 * 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.

查看更多
叼着烟拽天下
5楼-- · 2020-02-10 15:19

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.

查看更多
登录 后发表回答