Colon after method declaration?

PhpPhp 7

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVikastView Question on Stackoverflow
Solution 1 - PhpfireView Answer on Stackoverflow
Solution 2 - PhpMrCodeView Answer on Stackoverflow