Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double colon in function declaration

While reading a post on Medium, I stumbled upon a function signature I couldn't understand.

public function index(): Response
{
    $posts = $this->getDoctrine()
                ->getRepository(Post::class)
                ->findAll();
    return $this->render('posts/list.html.twig', ['posts' => $posts]);
}

What is the purpose of : Response in this case ? Is it specific to Symfony ?

like image 441
Arthur Attout Avatar asked Jun 01 '26 17:06

Arthur Attout


1 Answers

PHP 7 adds support for return type declarations. Similarly to argument type declarations, return type declarations specify the type of the value that will be returned from a function. The same types are available for return type declarations as are available for argument type declarations.

Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

PHP 7.1 adds a nullable return type, declared like : ?string

Some example:

function getNothing(): void {
    return; // valid
}

function getNothing(): void {
    // do nothing
    // valid
}

function getAge(): ?int  {
    return null; // valid
}

function getAge(): ?int  {
    return 18; // valid
}

function getAge(): int  {
    return 18; // valid
}

function getAge(): ?int  {
    return null; // valid
}

function getAge(): int  {
    return null; // error
}
like image 163
goto Avatar answered Jun 03 '26 05:06

goto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!