Top 10 pitfalls you need to avoid in PHP
1. Do not use the mysql_ class function
Finally, you no longer need to see the prompts suggesting not to use the mysql_ function. Because PHP 7 completely removes them from the core, this means you need to move to better mysqli_ class functions, or the 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, 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 quote unless necessary
I personally don’t like passing parameters by quote. 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 example 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 use it in code. Writing SQL statements, so I say it's 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 too 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 profilers to unit testing frameworks, from Mailchimp APIs to Twitter Bootstrap, everything is just a click of a button (or a command away) away, so 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!
Thank you everyone for reading, I hope you will benefit a lot.
This article is reproduced at: https://www.cnblogs.com/summerblue/p/8778819.html
Recommended tutorial: "php tutorial"
The above is the detailed content of Top 10 pitfalls you need to avoid in PHP. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
