RE: [PHP-DEV] Introducing "Array Of" RFC
Hey Joe,
> I don't want to set out to do anything that is bad, however, I think
> the performance thing is not really a massive concern, after all it's
> not very difficult for something innocent to incur a measurable overhead:
>
> https://eval.in/91920
It can be fairly fast for one call only, but imagine you have those type hints all over the place.
I really don't think it is a good idea to introduce something which we both now is far from
ideal. Yet, I like the idea
behind this RFC and think we should think it over and come up with a better implementation.
Your last comment was actually thought-provoking
> The idea to change the hashtable wouldn't work anyway (for the OP of
> the idea): you can have a reference to a variable that is a member of an
> array and change it's type without executing any opcodes related to
> hashtable manipulation.
So I sat down and coded an example in PHP. Maybe it can help this RFC to go further. You can find it
here:
https://github.com/robstoll/phputils/blob/master/TypedArray.php
Seems like the implementation is robust enough for the dirty reference hack (as mentioned by you) by
chance. Yet, one
could still inject invalid types via Reflection. It's not possible to prohibit that as far as I
know.
Brief overview of the implementation
- works for all types (bool, int, float, string, array, resource, callable, and class/interface)
- initialisation in two different ways
$foos = new TypedArray(Types::T_CLASS_OR_INTERFACE, "Foo");
$bars = TypedArray::createFromArray(Types::T_INT, [1,2,3, 'a'=5, 'a'=>9]);
- type hinting can be used as follows:
/**
* @param TypedArray<int> $arr
*/
function foo(TypedArray $arr){
$arr->checkIsSameType(Types::T_CLASS_OR_INTERFACE, "Foo");
}
I have not yet implemented Iterator as interface but that could be added easily
This implementation has of course drawbacks compared to the RFC:
- it is not obvious what type TypedArray contains just from reading the signature (needs the
additional documentation)
- needs one extra line of code to check if actually the given TypedArray is of the correct type
And advantages:
+ is already possible with the current PHP version
+ type hint check O(1)
+ add element check O(n)
+ one can still pass a normal array with the initialise syntax (does more or less the same as your
implementation):
foo(TypedArray::createFromArray(Types::T_INT, $arr);
If we would substitute the one additional line with some syntactic sugar then we would have already
a nice
implementation IMO.
Cheers,
Robert
Thread (73 messages)