Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to using colon in PHP function

Tags:

php

I found that someone writes code like this:

class Abc
{
    public function foo(int $bar) : string {}
}

What does : mean in a function? What's the effect of changing string to bool or array or int?

I just don't understand why we need : xxx, and when to use it?

like image 521
user7440009 Avatar asked Jan 19 '17 09:01

user7440009


Video Answer


2 Answers

That is the return type declaration, a feature introduced with PHP 7.

The type that you see after the colon, is the type that will be returned with the function.

There are 2 options:
By default the returned value will be converted to the type that needs to be returned.
In your case it will always be converted to a string.

If strict typing is enabled (by declare(strict_types=1);), the output needs to be a string, or it will throw a TypeError.

Either way: as a developer you are always sure that the return type is a string in this case.

It is not obligatory to define the return type, so you can leave it if you don't want it. The return type in that case can be anything.

like image 120
Blaatpraat Avatar answered Oct 14 '22 02:10

Blaatpraat


It's declares the return type for the function.

function foo (int $bar) : string { }

The int $bar part says that the $bar parameter must be an integer, and the : string part says the function will return a string. If the function is not passed an int or does not return a string, a TypeError will be thrown.

like image 4
Jake Taylor Avatar answered Oct 14 '22 01:10

Jake Taylor