This article shares with you ten pitfalls that you need to avoid in PHP 7. It has a certain reference value. Friends in need can refer to it
1. Do not use mysql_ class functions
Finally, you no longer need to see the prompts suggesting not to use mysql_
functions. Because PHP 7 completely removes them from the core, this means you should move to better mysqli_
-like functions, or a more flexible PDO layer.
2. Don’t write useless code
This seems like a brainless suggestion, but as the speed of PHP7 increases, it masks some problems and makes it increasingly important. Don’t be complacent just because switching to PHP7 makes your site faster.
To understand the importance of speed and how to do it better, check out our article Beginner’s Guide to Acceleration Optimization.
As a developer, you should ensure that scripts are loaded on demand, combined when possible, write efficient database queries, use caching if possible, etc.
3. Do not use the PHP closing tag at the end of the file
If you take a casual look, you will find that most WordPress core code files omit the PHP closing tag at the end. In fact, the Zend Framework specifically disables closing tags. It is not required by PHP, omitting it at the end of the file ensures no extra whitespace at the end.
4. Don’t pass parameters by reference unless necessary
I personally don’t like passing parameters by reference very much. I certainly know that it can be useful in some situations, but most of the time it makes the code difficult to understand, difficult to follow, and difficult to predict the results.
People think that references make their code faster, but as this article from The Respectable PHP Programmer points out, that's not the case.
PHP’s built-in shuffle()
or sort()
function is a bad case of parameter passing by reference. It modifies the original array instead of returning a shuffled or sorted array, which is completely against our wishes.
5. Don’t use queries in loops
The worst thing is to use database queries in loops. It will put unnecessary stress on the system, and most likely, you can get the same results faster by using the query outside the loop. When I encounter a situation where I have to use it this way, I usually solve it by splitting it into two queries to construct an array. Then loop over the array without looping the query.
There may be some exceptions to this due to the way WordPress operates. get_post_meta()
will get a metadata from the database, which you can use in a loop if you are looping through the metadata for a specific post. This is because WordPress actually takes all the metadata and caches it when you first use it. Subsequent calls actually call cached data rather than calling the database.
The best way to solve these problems is to read the function documentation and use something like a query listener.
6. Don't use *
in SQL queries. Well, this is more of a MySQL question, but we prefer to write SQL statements in code, so I say this is a Fair game. In any case, if you can avoid using wildcards, don't use them, especially if your database has many fields.
Explicitly specify the fields you need and retrieve only those fields. This helps save memory, protect data, and make things clearer.
On the SQL side, learn as much as possible about the functions available to you and test the speed. When calculating averages, sums, and calculating similar numbers, use SQL built-in functions instead of PHP functions. If you're not sure how fast a query is, test it and compare it with other approaches to choose the best one.
7. Don’t trust user input
It’s not wise to trust user input. For user input, there is always a need to filter, sanitize, escape, validate, and use fallbacks. There are three problems with user input: it is impossible for us developers to consider all possibilities, frequent mistakes, and intentionally malicious input.
A well-thought-out system can prevent all of these problems. When using a database, be sure to use built-in functions such as filter_var()
to check validity, escape, and do whatever else you can.
WordPress has a bunch of functions to help you. Have a look at this article to learn more about Validating, escaping and sanitising user data.
8. Don’t be smart
Your goal is to write elegant code that clearly expresses your wishes. You may save 0.01 seconds on each page's loading time by shortening variable names, using multi-level ternary logic operations, and other tricks, but it's not worth the loss compared to the consequences of causing you and your team headaches and difficulty in maintaining.
Name variables appropriately and write code documentation in a concise and clear way. It's better to use a standardized object-oriented coding style and more or less document it, rather than using lots of inline code comments.
9. Don’t reinvent the wheel
PHP has been around for a while, and website development has been around even longer. Whatever you have done, someone else has done it before. Don’t be afraid to rely on others for support. Github, Composer, and Packagist are all your mentors.
From logging to color processors, from analyzers to unit testing frameworks, from Mailchimp APIs to Twitter Bootstrap, everything is available with the push of a button (or typing of a command), go use them !
10. Don’t overlook other languages
If you are a PHPer, it is now standard practice to know at least HTML, CSS, Javascript and MySQL. When you can handle these languages well, it's time to learn Javascript again. Javascript is not jQuery. You should learn Javascript to utilize jQuery effectively.
I also recommend learning everything object-oriented in PHP. It's a lifesaver and will improve your code by orders of magnitude. It can also open doors to languages like C# and Java, which can make it easier to understand object-oriented programming (OOP) once you have experience with them.
Expand your knowledge by learning package management, build scripts, Coffeescript, LESS, SASS, YAML, template engines, and other useful tools. I also wholeheartedly recommend looking at other frameworks, especially Laravel.
When you are good enough at these, consider Ruby, Ruby on Rails and app development for Android, iPhone, and Windows Phone? You may think these are pointless because they are outside of your comfort zone and job requirements, but they are exactly the point. Every language has some useful pedagogical knowledge and some harmless extras. All top PHP developers know other programming languages, this is no accident!
Related recommendations:
Ten tips for using Redis correctly
Ten advanced tips for PHP_PHP programming
The above is the detailed content of Ten pitfalls you need to avoid in PHP 7. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
