Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
972 views
in Technique[技术] by (71.8m points)

oop - Why is it possible to have an interface without a return type in PHP?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...