How to define the return type of a function that returns an array of objects in php 8.2 [duplicate]
For example, I develop an api and I have to type all my functions, I have a function that returns a list of movements, so how to define the return type of my function ? I tried to do this : public function getAllMovements() : Movement[] <> But it does’nt work, i work with laravel 10.
I think you saw a TypeScript mechanism and trying to implement it in PHP . As I know you can’t. You can use predefined sets like, array , resource , collection , bool etc.
2 Answers 2
If you want it only available in documentation, it’s supported by phpdoc like so:
Else, I think you should create a strongly typed collection yourself, for example answered here: https://stackoverflow.com/a/73738459/3090890
class MovementCollection extends ArrayObject < public function __construct(array $items = []) < foreach ($items as $item) < $this->validate($item) > > .
In API’s its not uncommon to build typed collections like that.
«In API’s its not uncommon to build typed collections like that» — That’s probably because of the absence of generics.
I have defined a Movement Resource that return a movement collection
class MovementResource extends JsonResource < /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable */ public function toArray($request) < return parent::toArray($request); >>
and in my function I have defined the resource as a return type and everything is working correctly
public function getAllMouvements() : MovementResource <>
With this we are sure that the return type will be a collection of movements.
I still think my code is relevant to his question, maybe i clarified with the comment inside of the function.
I do think this is what the OP means. I have a function that returns a list of movements, so how to define the return type of my function ? It is the return type of the function and not the type of the contents of the array. If it was to check what’s inside the array and also typecheck that, it would not be possible IMO.
@Wimanicesir It would be if OP is able to create a class, e.g. MovementCollection , which inherits ArrayAccess as pointed out in the duped question
This is a correct answer, the answer simply is: either define array as return type (can’t so Array
Возврат значений
Значения возвращаются при помощи необязательного оператора возврата. Возвращаемые значения могут быть любого типа, в том числе это могут быть массивы и объекты. Возврат приводит к завершению выполнения функции и передаче управления обратно к той строке кода, в которой данная функция была вызвана. Для получения более детальной информации ознакомьтесь с описанием return .
Замечание:
Если конструкция return не указана, то функция вернет значение NULL .
Использование выражения return
Пример #1 Использование конструкции return
Функция не может возвращать несколько значений, но аналогичного результата можно добиться, возвращая массив.
Пример #2 Возврат нескольких значений в виде массива
function small_numbers ()
return array ( 0 , 1 , 2 );
>
list ( $zero , $one , $two ) = small_numbers ();
?>?php
Для того, чтобы функция возвращала результат по ссылке, вам необходимо использовать оператор & и при описании функции, и при присвоении переменной возвращаемого значения:
Пример #3 Возврат результата по ссылке
Для получения более детальной информации о ссылках обратитесь к разделу документации Подробно о ссылках.
Объявление типов возвращаемых значений
В PHP 7 добавлена возможность объявлять тип возвращаемого значения. Аналогично объявлению типов аргументов можно задать тип значения, которое будет возвращаться функцией. Типы, которые можно объявить для возвращаемых значений те же, что и для аргументов фукнций.
Режим строгой типизации также работает для объявлении типа возвращаемого значения. В обычном режиме слабой типизации возвращаемое из функции значение приводится к корректному типу. При строгой типизации возвращаемое значение должно быть заданного типа, иначе будет выброшено исключение TypeError.
Замечание:
Если переопределяется родительский метод, возвращаемое значение дочернего метода должно быть того же типа, что и родительского. Если в родительском методе не задан тип возвращаемого значения, то и дочерний метод этот тип может не объявлять.
Примеры
Пример #4 Обычное объявление типа возвращаемого значения
// Будет возвращаться значение типа float.
var_dump ( sum ( 1 , 2 ));
?>
Результат выполнения данного примера:
Пример #5 То же в режиме строгой типизации
function sum ( $a , $b ): int return $a + $b ;
>
var_dump ( sum ( 1 , 2 ));
var_dump ( sum ( 1 , 2.5 ));
?>
Результат выполнения данного примера:
int(3) Fatal error: Uncaught TypeError: Return value of sum() must be of the type integer, float returned in - on line 5 in -:5 Stack trace: #0 -(9): sum(1, 2.5) #1 thrown in - on line 5
Пример #6 Возврат объектов
function getC (): C return new C ;
>
Результат выполнения данного примера:
Php return type collection
Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See return for more information.
Note:
If the return is omitted the value null will be returned.
Use of return
Example #1 Use of return
A function can not return multiple values, but similar results can be obtained by returning an array.
Example #2 Returning an array to get multiple values
function small_numbers ()
return [ 0 , 1 , 2 ];
>
// Array destructuring will collect each member of the array individually
[ $zero , $one , $two ] = small_numbers ();
?php
// Prior to 7.1.0, the only equivalent alternative is using list() construct
list( $zero , $one , $two ) = small_numbers ();
To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable:
Example #3 Returning a reference from a function
For more information on references, please check out References Explained.
User Contributed Notes 10 notes
PHP 7.1 allows for void and null return types by preceding the type declaration with a ? — (e.g. function canReturnNullorString(): ?string)
However resource is not allowed as a return type:
function fileOpen ( string $fileName , string $mode ): resource
$handle = fopen ( $fileName , $mode );
if ( $handle !== false )
return $handle ;
>
>
$resourceHandle = fileOpen ( «myfile.txt» , «r» );
?>
Errors with:
Fatal error: Uncaught TypeError: Return value of fileOpen() must be an instance of resource, resource returned.
Developers with a C background may expect pass by reference semantics for arrays. It may be surprising that pass by value is used for arrays just like scalars. Objects are implicitly passed by reference.
# (1) Objects are always passed by reference and returned by reference
function obj_inc_x ( $obj ) $obj -> x ++;
return $obj ;
>
$obj2 = obj_inc_x ( $obj );
obj_inc_x ( $obj2 );
print $obj -> x . ‘, ‘ . $obj2 -> x . «\n» ;
# (2) Scalars are not passed by reference or returned as such
function scalar_inc_x ( $x ) $x ++;
return $x ;
>
$x2 = scalar_inc_x ( $x );
scalar_inc_x ( $x2 );
# (3) You have to force pass by reference and return by reference on scalars
$x2 =& scalar_ref_inc_x ( $x ); # Need reference here as well as the function sig
scalar_ref_inc_x ( $x2 );
# (4) Arrays use pass by value sematics just like scalars
function array_inc_x ( $array ) $array < 'x' >++;
return $array ;
>
$array = array();
$array [ ‘x’ ] = 1 ;
$array2 = array_inc_x ( $array );
array_inc_x ( $array2 );
print $array [ ‘x’ ] . ‘, ‘ . $array2 [ ‘x’ ] . «\n» ;
# (5) You have to force pass by reference and return by reference on arrays
$array = array();
$array [ ‘x’ ] = 1 ;
$array2 =& array_ref_inc_x ( $array ); # Need reference here as well as the function sig
array_ref_inc_x ( $array2 );
print $array [ ‘x’ ] . ‘, ‘ . $array2 [ ‘x’ ] . «\n» ;
Be careful about using «do this thing or die()» logic in your return lines. It doesn’t work as you’d expect:
function myfunc1 () return( ‘thingy’ or die( ‘otherthingy’ ));
>
function myfunc2 () return ‘thingy’ or die( ‘otherthingy’ );
>
function myfunc3 () return( ‘thingy’ ) or die( ‘otherthingy’ );
>
function myfunc4 () return ‘thingy’ or ‘otherthingy’ ;
>
function myfunc5 () $x = ‘thingy’ or ‘otherthingy’ ; return $x ;
>
echo myfunc1 (). «\n» . myfunc2 (). «\n» . myfunc3 (). «\n» . myfunc4 (). «\n» . myfunc5 (). «\n» ;
?>
Only myfunc5() returns ‘thingy’ — the rest return 1.
With 7.1, these are possible yet;
function ret_void (): void // do something but no return any value
// if needs to break fn exec for any reason simply write return;
if (. ) return; // break
// return null; // even this NO!
>
$db -> doSomething ();
// no need return call anymore
>
function ret_nullable () ? int if (. ) return 123 ;
> else return null ; // MUST!
>
>
?>
Functions which return references, may return a NULL value. This is inconsistent with the fact that function parameters passed by reference can’t be passed as NULL (or in fact anything which isnt a variable).
if ( testRet () === NULL )
echo «NULL» ;
>
?>
parses fine and echoes NULL
PHP 7 return types if specified can not return a null.
For example:
declare( strict_types = 1 );
function add2ints ( int $x , int $y ): int
$z = $x + $y ;
if ( $z === 0 )
return null ;
>
return $z ;
>
$a = add2ints ( 3 , 4 );
echo is_null ( $a ) ? ‘Null’ : $a ;
$b = add2ints (- 2 , 2 );
echo is_null ( $b ) ? ‘Null’ : $b ;
exit();
Output :
7
Process finished with exit code 139
Be careful when introducing return types to your code.
Only one return type can be specified (but prefacing with ? allows null).
Return values of a type different to that specified are silently converted with sometimes perplexing results. These can be tedious to find and will need rewriting, along with calling code.
Declare strict types using «declare(strict_types=1);» and an error will be generated, saving much head-scratching.
You may specify child return type if there is no parent:
class A public function f ( $a )
return 1 ;
>
>
class B extends A public function f ( $a ): int // + return type, OK
return 1 ;
>
>
class C extends A public function f ( int $a ) // + argument type, WARNING
return 1 ;
>
>
?>
Note: the function does not have «alternative syntax» as if/endif, while/endwhile, and colon (:) here is used to define returning type and not to mark where the block statement begins.
Declaring a collection of objects as return type is not implemented and forbidden:
class Child <>
function getChilds (): Child [] return [(new Child ()), (new Child ())];
>
var_dump ( getChilds ());
// Returns: Parse error: syntax error, unexpected ‘[‘, expecting ‘ ?>
We have to use:
class Child <>
function getChilds (): array
return [(new Child ()), (new Child ())];
>
var_dump ( getChilds ());
// Returns:
/*
array (size=2)
0 =>
object(Child)[168]
1 =>
object(Child)[398]*/
?>
Idem for function parameter:
function setChilds ( Child [] $childs )<>
// Not allowed
function setChilds (array $childs )<>
// Allowed
?>