Type hinting in PHP 7 - array of objects -


maybe missed there option define function should have argument or return example array of user objects?

consider following code:

<?php  class user {     protected $name;      protected $age;      /**      * user constructor.      *      * @param $name      */     public function __construct(string $name, int $age)     {         $this->name = $name;         $this->age = $age;     }      /**      * @return mixed      */     public function getname() : string     {         return $this->name;     }      public function getage() : int     {         return $this->age;     } }  function finduserbyage(int $age, array $users) : array {     $result = [];     foreach ($users $user) {         if ($user->getage() == $age) {             if ($user->getname() == 'john') {                 // complicated code here                 $result[] = $user->getname(); // bug             } else {                 $result[] = $user;             }         }     }      return $result; }  $users = [     new user('john', 15),     new user('daniel', 25),     new user('michael', 15), ];  $matches = finduserbyage(15, $users);  foreach ($matches $user) {     echo $user->getname() . ' '.$user->getage() . "\n"; } 

is there option in php7 tell function finduserbyage should return array of users? expect when type hinting added should possible haven't found info type hinting array of objects it's not included in php 7. if it's not included, have clue why not included when type hinting added?

it's not included.

if it's not included, have clue why not included when type hinting added?

with current array implementation, require checking array elements @ runtime, because array contains no type information.

it has been proposed php 5.6 rejected: rfc "arrayof" - interestingly not because of performance issues turned out neglible, because there no agreement in how should implemented. there objection incomplete without scalar type hints. if interested in whole discussion, read in mailing list archive.

imho array type hints provide benefit typed arrays, , i'd love see them implemented.

so maybe it's time new rfc , reopen discussion.


partial workaround:

you can type hint variadic arguments , write signature as

function finduserbyage(int $age, user ...$users) : array 

usage:

finduserbyage(15, ...$userinput); 

in call, argument $userinput "unpacked" single variables, , in method "packed" array $users. each item validated of type user. $userinput can iterator, converted array.

unfortunately there no similar workaround return types, , can use last argument.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -