• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Pipe operator is coming to PHP !

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,562
Баллы
155


A new operator is coming to PHP: the pipe ! (|>)

Just like in linux, you will now be able to chain multiple commands together.

What it is


This operator will help us make the code more readable and expressive.

Before:


$result = ucfirst(strtolower(str_replace('_', ' ', "HELLO_WORLD")));




With the pipe operator:


$result = "HELLO_WORLD"
|> str_replace('_', ' ', ...)
|> strtolower(...)
|> ucfirst(...);




The other way to make the first example readable is to use a temporary variable:


$result = "HELLO_WORLD";
$result = str_replace('_', ' ', $result);
$result = strtolower($result);
$result = ucfirst($result);




The pipe operator gives you clean style to chain calls.

How to use it


In PHP, we use callables so we have multiple ways to use it:

  • userland functions
  • built-in functions
  • static class methods
  • lambda functions
  • arrow-functions
  • invokable classes
  • first-class callables.

Here’s a demo:


$result = "42"
|> intval(...)
|> fn($x) => $x * 2
|> function(int $x): string { return "Value: $x"; }
|> new Transformer()
|> [MathHelper::class, 'addExclamation']
|> format_output(...);

echo $result; // Value: 84!



The drawback


“Perfect,” you might think — and almost!

But there’s a small limitation.

The pipe operator only works when the result of the previous can be passed as the first argument of the next callable.
So while the pipe operator makes code cleaner, it does have some functional-style constraints you’ll need to keep in mind.

Conclusion


The pipe operator brings a fresh, functional touch to PHP — making our code flow as smoothly as our ideas.



Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу