Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class method weirdness (PHP)

Tags:

php

I encountered a class which has the following method:

class Period
{
/** @var \DateTime */
public $startDate;

/** @var \DateTime */
public $endDate;

public static function create(DateTime $startDate, $endDate): Period
{
    return new static($startDate, $endDate);
}
}

My question is about the part after the create(...) - the ": Period". I have never seen this before and can't find any documentation about it (mainly because I have no clue what to look for). Can anyone shed some light on this?

like image 298
Dominique Vermeersch Avatar asked Sep 30 '26 05:09

Dominique Vermeersch


1 Answers

This is new in PHP version 7 and above. It's called return type declarations. In the example you posted it requires the method create to return an object of Period.

An easier example would be:

function giveMeAnInt() : int {
    return 1;
}

Above code is valid because it returns an integer.

function giveMeAnInt() : int {
    return "Hello";
}

This is not valid and will return a fatal error "FATAL ERROR Uncaught TypeError: Return value of giveMeAnInt() must be of the type integer, string returned"

like image 93
Daan Avatar answered Oct 01 '26 18:10

Daan



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!