为什么在PHP中有一个没有返回类型的接口?

str*_*ade 13 php oop

为什么可以在不指定返回类型的情况下创建接口?为什么不能使这个接口无法使用?

这使它更清楚:

Interface run
{
    public function getInteger();
}

class MyString implements run
{    
    public function myNumber()
    {

    }

    public function getInteger()
    {  
        return "Not a number";
    }    
}
Run Code Online (Sandbox Code Playgroud)

在Java中,每个接口都有一个类似的返回类型Integer,StringVoid

我知道PHP不幸是一种松散类型的语言,但是没有解决这个问题的方法吗?

是否可以定义具有类似返回类型的接口Integer

Cha*_*les 19

仅在PHP7.0或更高版本支持函数/方法参数或返回值的类型提示

请查看详细信息:http: //php.net/manual/en/migration70.new-features.php

如果您使用PHP5,那么当前接受的做法是使用phpdoc注释来指示"合同"存在.

/** 
 * Does something.
 * @return int
 **/
public function getInteger() { return 1; }
Run Code Online (Sandbox Code Playgroud)

如果代码违反了"合同",我建议找到原始编码器并让他们修复它和/或提交错误和/或自己修复它,如果它在你自己的代码库中.

  • 此答案中列出的RFC已过期.最近的RFC是[这里](https://wiki.php.net/rfc/return_types).它已被接受并存在于PHP7中. (5认同)

Mae*_*lyn 5

不,那里没有.你自己说的原因:PHP是松散的类型.
您可以在PHPDoc中有提示,或者检查您使用接口函数的函数中的类型,如果除了整数之外还得到其他内容,则抛出InvalidArgumentException.


Sco*_*pey 5

应该注意的是,现在可以使用PHP7(在撰写本文时只发布了Beta1)

可以使用以下语法:

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"
    }    
}
Run Code Online (Sandbox Code Playgroud)