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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With