Как решить эту устаревшую функцию каждый php
С PHP 7.2 each устарел. В документации сказано:
Предупреждение Эта функция УСТАРЕЛА с PHP 7.2.0. Полагаться на эту функцию крайне не рекомендуется.
Как я могу обновить свой код, чтобы избежать его использования? Вот некоторые примеры:
7 ответов
В первых двух примерах вы можете использовать key и current для назначения нужных вам значений.
В этих случаях вы можете использовать next для перемещения курсора позже, но это может не потребоваться, если остальная часть вашего кода не зависит от этого.
В третьем случае я бы предложил вместо этого использовать цикл foreach и назначать $kv внутри цикла.
В четвертом случае похоже, что ключ игнорируется в list , поэтому вы можете назначить текущее значение.
Как и в первых двух случаях, может потребоваться $this->cache_data курсор к next зависимости от того, как остальная часть вашего кода взаимодействует с $this->cache_data .
№ 5 можно заменить на цикл for.
Вы можете создать свою собственную функцию each() используя key(), current() и next(). затем замените ваши вызовы этой функцией, например так:
То, что вам определенно не следует делать, это поместить функцию «обратно в php», добавив ее в параметр auto_prepend_file в php.ini.
Затем создайте файл и введите в функцию упаковщик function_exists.
По сути, это объявляет функцию до запуска вашего php-приложения. Когда ваше приложение пытается запустить каждую функцию, оно будет использовать вашу версию.
Это абсолютно не тот способ, которым вы должны подходить к этой проблеме, особенно на производстве! Тем не менее, вы разработчик с ограничениями по времени, и вы просто хотите попробовать произвольные фреймворки для вашего следующего проекта, и они не были обновлены для работы на вашем локальном сервере разработки, не свернув вашу версию php.
Когда вы посвятите себя созданию базы кода для своего проекта, пожалуйста, внесите изменения в принятый ответ, потому что они работают.
Я использовал эмуляцию Wee Zel каждой функции
2019+ Мгновенное обновление each()
На самом деле существует множество случаев, в которых each() может быть заменен, поэтому в этом вопросе так много разных ответов.
Вы можете заменить один за другим вручную. Но разве нет лучшего способа?
Я помогаю переносить проекты, в которых есть такие случаи 150+. Я ленивый, поэтому я сделал инструмент под названием Rector, который преобразует код описанным выше способом (+ есть еще случаи, но я не хочу спамить ответ).
Это часть набора php72 .
Просто установите и используйте его:
Я надеюсь, что это поможет вам с вашей миграцией.
Если есть какая-то ошибка или аномалия, то Ректор пропустил дело. Создайте проблему, чтобы мы могли ее исправить и заставить ее работать для каждого возможного случая.
Must replace Each() function in PHP code? Each() to foreach()
Get the solution ↓↓↓
I must change the PHP version to 8.1 on a old code.
but i’m not sure that is right what i do. old code:
Is that right to swap from the each() to foreach()?
Under PHP8.1 it does not work, but it could be that my problem is on a other place. Under PHP 7.4 all is fine


Answer
Solution:
There are a number of changes between PHP 5, 7 and 8. A great place to start for 8.1 is on the PHP page. Other mitigation version advice is also listed on that PHP page.
There is more than one change that has affected your posted code, and that is what is causing the confusion.
The each() to foreach() change is only one and has nothing to do with the posted error message (which is self explanatory).
Fatal error: Uncaught TypeError: mktime(): Argument #1 ($hour) must be of type int.
For that particular error, you can change:
Using (int)$varible will cast the String (or other type) value to an int .
There could be other error messages that follow once you fix that issue. Suggest you read the error message and cross check the PHP docs.
Share solution ↓
Additional Information:
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites. The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.
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
This package returns the legacy each() function which has been removed in PHP 8.0. This can be useful when working with legacy code or with end-of-life packages which still make use of the each() function.
It is therefore not really a polyfill but rather a shim as it provides legacy functionality to modern-day software instead of vice versa. I have still chosen the name polyfill as this term is usually top of mind irrespective of the direction of the port.
Each() устарела, а чем заменить не сказали
сма DAEWOO DWD M1029A чем заменить транс, трансформатор в обрыве, чем заменить
день добрый. модуль PN:361430A950 первичная транса в обрыве . может кто подскажет параметры .
Чем можно заменить заменить toggle() ?
Добрый день, у меня такой вопрос. Чем можно заменить toggle(function(), function()); В ранних.
Устарела ли JavaEE
Подскажите пожалуйста, устарела или устаревает Java ee, а то я начал недавно ее изучать, а если да.
Книга устарела?
У меня есть книга за 1996 год. Намир Шамма "Основы С++ и объектно-ориентированного.