Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.5] Add array support to Optional #22417

Merged
merged 1 commit into from
Dec 16, 2017

Conversation

JosephSilber
Copy link
Contributor

@JosephSilber JosephSilber commented Dec 13, 2017

Lets you pass a maybe array to optional, then access one of its keys:

$location = optional($order->meta)['location'];

@taylorotwell
Copy link
Member

Is it super necessary since you could just do $order->meta['location'] ?? null?

@Miguel-Serejo
Copy link

I don't quite get what you're intending to fix here. Your tests would work just the same without the call to optional.
Quick tinker test:

>>> null['missing']
=> null
>>> ['present' => 'here']['present']
=> "here"

You're not testing for missing keys, which is the one thing that a call to optional might be able to help. As @taylorotwell mentioned, the null coalescing operator works just fine for that sort of call, but having optional array access could arguably improve consistency when you have a lot of objects and arrays you're trying to optionally access, or maybe even help with chaining this sort of call.

@JosephSilber
Copy link
Contributor Author

JosephSilber commented Dec 14, 2017

@36864 Wow! Didn't even know that works in PHP 😱

Even now that I do know, I don't ever want to use that! Feels utterly wrong, and I have a feeling this might change in a future version of PHP. Silently ignoring array access on null is not the type of thing a sane language should allow (╯°□°)╯︵ ┻━┻)

@Miguel-Serejo
Copy link

You're using a language that lets you use variables without so much as a type hint, we've passed "sane" a long time ago.

This is documented behavior.

Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.
source: http://php.net/manual/en/language.types.array.php

Null is a scalar value, so attempting to access any position on it would naturally result in null.

As for not wanting to use it, that doesn't jive with this PR. You literally made a PR because you wanted to access null values as arrays. PHP lets you do that straight out of the box.

@taylorotwell taylorotwell merged commit 2564437 into laravel:5.5 Dec 16, 2017
@JosephSilber JosephSilber deleted the optional-array branch March 25, 2018 02:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants