Перейти к содержимому

Php create function чем заменить

  • автор:

replacing create_function() with something else for PHP8 [duplicate]

So I have a plugin that was working fine previously, but for a few days now it is throwing me an error as:

PHP Fatal error: Uncaught Error: Call to undefined function create_function()

After a bit of searching, I found out that this is because create_function() is deprecated in PHP 8.

Now the exact line that causes the issue is this:

I tried changing this to:

But it’s not working. So it would be great if someone could point me in the right direction also I am very new to PHP.

Name already in use

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.MD

PHP 8 create_function replacement

This repository contains a replacement for the function create_function that has been removed from PHP 8

Function create_function() is Deprecated in PHP 7.2 — How to Migrate?

Updated Rector YAML to PHP configuration, as current standard.

If there would be "Miss Deprecation of PHP 7.2", create_function() would definitely win. They can be very complex, tricky and very hard convert to PHP code. Moreover without tests.

Do you have over 5 create_function() pieces in your code? Let’s see how to migrate them.

Why is this deprecated? Well, the string arguments of few functions behaves like eval() — that’s evil.

And what about quotes?

You don’t want to think which if " or ` breaks the code — you want make code.

I think it’s a good move, so how do we refactor them? Let’s start with simple code:

How would you refactor this to anonymous function?

(Pause for deep thinking. )

  • 1st argument = function arguments
  • 2nd argument = function body

Also, notice the \$matches → $matches . That’s because quote escaping.

What about this one?

How would you refactor this to anonymous function?

(Pause for deep thinking. )

The "min(b^2+a, a^2,b) = " is still a string, because it was escaped string in a string.

Too easy for you? Damn, you’re smart.

Can you handle this?

How would you refactor this to anonymous function?

(Pause for deep thinking. )

Ok, but you won’t make this code snippet I found in Drupal/Wordpress:

How would you refactor this to anonymous function?

(Pause for deep thinking. )

Who did forget use ($xd) ? An anonymous function can’t access variables that are not passed as arguments, so without this would crash.

And we could continue and continue with more edgy cases. but I bet you’re looking for a solution for your specific function. Well, you could ask on StackOverflow (181 results and counting), but posting each of your 10 cases might get you banned. I have good news for you.

Today in 2019 (almost there), you can instantly upgrade your code and it will take you less time to install & run, then read this whole post so far.

Just setup Rector and run it:

Happy instant upgrading!

Do you learn from my contents or use open-souce packages like Rector every day?
Consider supporting it on GitHub Sponsors. I’d really appreciate it!

После перехода на PHP 7.2.9 сайт работает некорректно

После перехода на последнюю версию PHP, т. е. PHP 7.2.9, некоторые страницы не открываются, а загружаются только после команды «обновить». Такое ощущение, как-будто срабатывает редирект. Особенно заметно на гаджетах: каждая ссылка ведет на белый экран, посредине которого написано, что сайт временно недоступен или переехал на другой адрес, страницы открываются только после перезагрузки.

В логах нашел следующие ошибки:

Deprecated: Function create_function() is deprecated in /var/www/h33115/data/www/stimylrosta.com.ua/libraries/rokcommon/RokCommon/Service/ContainerImpl.php on line 460

Deprecated: Function create_function() is deprecated in /var/www/h33115/data/www/stimylrosta.com.ua/libraries/rokcommon/RokCommon/Service/ContainerImpl.php on line 461

Уже все перепробовал, не знаю, куда дальше рыть. Помогите, пожалуйста.

stimyl:
Здравствуйте.
Сайт на CMS Joomla версия 3.8. — https://stimylrosta.com.ua
После перехода на последнюю версию PHP, т. е. PHP 7.2.9, некоторые страницы не открываются, а загружаются только после команды «обновить». Такое ощущение, как-будто срабатывает редирект. Особенно заметно на гаджетах: каждая ссылка ведет на белый экран, посредине которого написано, что сайт временно недоступен или переехал на другой адрес, страницы открываются только после перезагрузки.

В логах нашел следующие ошибки:

Deprecated: Function create_function() is deprecated in /var/www/h33115/data/www/stimylrosta.com.ua/libraries/rokcommon/RokCommon/Service/ContainerImpl.php on line 460
Deprecated: Function create_function() is deprecated in /var/www/h33115/data/www/stimylrosta.com.ua/libraries/rokcommon/RokCommon/Service/ContainerImpl.php on line 461

Уже все перепробовал, не знаю, куда дальше рыть. Помогите, пожалуйста.

что указано на строках с ошибками (460 и 461 строка)?

Пишет же, что функция create_function не поддерживается. Ругается на использование этой функции в библиотеке rokcommon. Видимо, это какое-то расширение в джумле, модуль, тема или еще что-то. Попробуйте обновить

ТС же пишет, что уже все перепробовал — ничего не помогает. Видимо уже пробовал обновлять, наверное уже узнал, что данная функция в php 7.2 считается устаревшей и перепробовал варианты ее замены на другие функции, конструкции https://www.google.ru/search?q=Deprecated:+Function+create_function()+is+deprecated+in+site:stackoverflow.com .

ТС не написал, что конкретно он перепробовал, «все» — понятие растяжимое. Вариантов тут все равно не много: либо попробовать обновить, либо ковырять библиотеку и менять create_function на замыкания, либо заменить это расширение на аналоги

Получается, что когда выключаю все активные модули сайт работает корректно. Стоит мне активировать какой-либо модуль и страницы не грузятся или грузятся туго. На др. шаблонах все ок. Может можно что-то предпринять, чтобы шаблон не менять?

stimyl, используемая по описанному в ошибке пути функция не поддерживается.

Предпринять здесь можно 2 варианта:

1. Не юзать данный модуль

2. Обновить функцию. Самому, руками, или через обновление плагина (если доступно).

Ну и третий вариант — понизить версию PHP.

Больше здесь ничего не сделать.

sergv:
stimyl, используемая по описанному в ошибке пути функция не поддерживается.
Предпринять здесь можно 2 варианта:
1. Не юзать данный модуль
2. Обновить функцию. Самому, руками, или через обновление плагина (если доступно).

Ну и третий вариант — понизить версию PHP.

Больше здесь ничего не сделать.

Здесь указано, что функция «create_function» объявлена УСТАРЕВШЕЙ, начиная с PHP 7.2.0 и ее использование крайне не рекомендовано.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *