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"
looks like this code belongs to time range api for php (class) , for more informations http://period.thephpleague.com/
Example : to create a new instance representing a given week :
<?php
public static Period::createFromWeek(int $year, int $week): Period
...
The $year parameter must be a valid year;
The $week parameter must be a valid week (between 1 and 53);
more examples here : http://period.thephpleague.com/examples/