Colon after method declaration?

可紊 提交于 2019-12-17 16:11:52

问题


public function getRecords(int $id): array;

Hi, can someone tell me what colon is doing here, in this method declaration inside PHP interface? Is this PHP 7 syntax and what array is meaning here? Method must return array or something else?


回答1:


Yes it's new syntax introduced in PHP 7 to declare the method returns an array.

http://php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration




回答2:


These are called Return Type declarations in PHP7. It indicates the type of value that the function returns, and it's not limited to arrays. For example, you can use float, int or even your own class:

class MyClass { }

function something(): MyClass {
    return new MyClass();
}

These are not just for readability. If the function returns a type other than that indicated, the value will be coerced into the indicated type. If it cannot be coerced, or strict mode is enabled, a Type Error will be thrown.



来源:https://stackoverflow.com/questions/40346754/colon-after-method-declaration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!