On Sunday, February 17, 2019 9:24:05 AM CST Girgias wrote: > Greetings internals, > > I would like to have your opinion on being able to type hint arrays and > objects which implement > array-like interfaces (notably ArrayAccess, Countable, and Iterator) as > currently if a function /method only needs one specific feature of an array > and is willing to accept array-like objects. > There are some rather repetitive boilerplate and the impossibility of using > type hints. > > An example of such a function, (where $arrayLike could be custom session > object) : > > /** ArrayAccess|array $arrayLike */ > public function checkCSRF($session) { > if (!is_array($session) && !($session instanceof ArrayAccess)) { > throw new Exception(); > } > // Check token > if (!isset($session['CSRF']) { > throw new Exception(); > } > // Do some more stuff ... > } > > As it can be seen this function/method doesn't need any of the other > properties of an array > such as Countability or Traversability to do its job. > However, in the current state of PHP, it is impossible to accept array-like > objects without > writing the initial if statement.
While I would like to see better consistency between arrays and array-ish objects in principle, in this case I think it's the wrong approach. You're using an associative array as a cheap anonymous struct. Don't do that. It's far less self-documenting, far less type safe, far more error prone, and far less performant. Just switching $session from an array-ish value to a class with public properties would make it use half as much memory. cf: https://steemit.com/php/@crell/php-use-associative-arrays-basically-never https://steemit.com/php/@crell/php-never-type-hint-on-arrays Making it easier to use anonymous-array-or-object-acting-like-anonymous-array would be a step backwards in every possible way. --Larry Garfield
signature.asc
Description: This is a digitally signed message part.