Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Colon after method declaration?

Tags:

php

php-7

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?

like image 936
Vikast Avatar asked Oct 31 '16 16:10

Vikast


People also ask

What Does a colon mean in DART?

It is a , -separated list of expressions that can access constructor parameters and can assign to instance fields, even final instance fields. This is handy to initialize final fields with calculated values.

What is colon after constructor?

It's called an initialization list. It initializes members before the body of the constructor executes.

What Does a colon mean in CPP?

Two colons (::) are used in C++ as a scope resolution operator. This operator gives you more freedom in naming your variables by letting you distinguish between variables with the same name.

What does colon mean in for loop C++?

Colon ':' is basically a operator which indicates that the y is inside x and assign the y's value to the elements of array one by one.


2 Answers

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

like image 96
fire Avatar answered Oct 17 '22 05:10

fire


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.

like image 32
MrCode Avatar answered Oct 17 '22 04:10

MrCode