php-plus / engine

✨ The Plus source code.
https://php-plus.com
91 stars 3 forks source link

Better type hinting #5

Open stancl opened 5 years ago

stancl commented 5 years ago
  1. arrays of X
public function addProducts(Product[] $products);
public function getProducts(): Product[];
  1. | in typehints
public function addProducts(Product[]|string[] $products):
  1. arrays with X keys and Y values
public function getProducts(): array<string, Product> // Product values, string keys
  1. It would be nice to be able to say "Collection of Products" (so a Collection with the first constructor argument being of type Product[]), but I have no idea how that should be notated.
olivernybroe commented 5 years ago

So this is basically adding union types and type hinted arrays.

I am not sure I am such a big fan of the key value syntax. Writing

Product[string]

Doesn't seem so clear that string is the key type. What about using the phpdoc way?

array<string, Product>

However I like your syntax when we don't use custom keys

stancl commented 5 years ago

I am not sure I am such a big fan of the key value syntax

Yeah, It's a bit confusing to read, since the key comes after the value. But I think it's some convention.

What about using the phpdoc way? array<string, Product>

Is this the phpdoc way? I haven't seen this yet.

Some people also do this:

array[string]Product
olivernybroe commented 5 years ago

@stancl sorry, it's the Psalm way. https://psalm.dev/docs/annotating_code/type_syntax/array_types/

stancl commented 5 years ago

I see. Psalm uses Foo[] and array<Foo, Bar> so it's already a bit standardized. I agree we should go with that. Updated my original comment.