|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2015-08-26 16:21 UTC] untuned20 at gmail dot com
Description:
------------
Allow for the ability to type hint a foreach loop.
Test script:
---------------
<?php
$classList = [/* List of classes */];
foreach($classList as $index => MyClass $class){}
foreach($classList as MyClass $class){}
class MyClass{
/* Methods and Properties */
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Nov 08 16:00:01 2025 UTC |
@untuned20 Do you have problem with foreach($classList as $class) { assert($class instanceof MyClass); } or something like this?I, for one, don't see the need for typed language constructs (heck, even languages like C++ have introduced the auto keyword because iterating over complex types was getting way to verbose). However, if this is something that is going to be implemented, there should be more thought put into this. Things to consider: - What is the expected behaviour if the type constraint is not met (catchable fatal, exception, warning, notice, ...?) - What about allowing multiple types? Do we need to introduce the vague mixed type-hint? - Scalars... do we implement type-hints for the keys, too (foreach ($array as int $key => string $value)) - If key type-hints are made possible, what do they do: the int $key hint should only allow numeric indexes or b) should skip over any key that is not numeric c) convert numeric strings to ints <- should this change the hashtable we're iterating over (probably not), but it might cause issues later on if it doesn't Tl;tr This request needs a lot more thought put into it, but really, there's no need as there are plenty of other ways to achieve this already: array_map($instanceList, function (MyClass $instance) { //element is guaranteed to be instance of MyClass here });