This article summed up the PHP good code style, share for everyone to reference, specific as follows:
1, avoid the use of magic number
This 18 doesn't quite understand why it should be like this.
You can define 28 in a variable, and the variable name indicates the meaning of the value.
$adult _age = 18;//of Adult age
if ($age < $adult _age) {
}
2, return result of function: Do not use a variable to store return result
Once you know the return result, you should return it immediately. The advantage of doing this is that you can reduce the error.
3, the function with a lot of parameters. Not more than three
If there are many parameters, try to aggregate into a model to pass in. such as an array, an instance can be.
Why do too many parameters affect the stability of the method?
For example, the modification will become very troublesome.
I understand now. This method requires a new parameter to be passed in, so the code that originally called the method has to be changed accordingly.
When you do interfaces, you often encounter similar problems.
function forgot ($userName, $email, $email _url, $format = ' json ')
There are three parameters.
It turns out that other people call this function,
Forgot ($userName, $email, $email _url, $format = ' json ');
Now that the requirements are changing, a new parameter needs to be added. What to do?
The original code will be modified. method is not stable. Or you can reopen a new way of adapting to your needs. You can either modify the caller's calling code.
But there's a kind of thing to do to avoid that.
The original pass parameter is made into an array form, as follows:
Forgot ($params =array (), $format = ' json ');
Aggregated into an array. This allows you to add any number of parameters.
How to understand: PHP engine built-in functions, with multiple parameters of the case?
Design flaws?
4, the parameter of the method contains the Boolean parameter.
This means that this method does not accomplish a single goal. violated a single duty. Adds complexity.
Let's think about it: how do you understand the problems in our code now?
More interested in PHP related content readers can view the site topics: "PHP object-oriented Program Design Primer", "PHP Mathematical Arithmetic Skills summary", "PHP Operations Office document tips (including word,excel,access,ppt)", "PHP Array ( Array) Operation Skills Encyclopedia, "PHP Data structure and algorithm tutorial", "PHP Programming Algorithm Summary", "PHP Regular Expression Usage Summary", and "PHP Common database Operation Skills Summary"
I hope this article will help you with the PHP program design.