Summary of php good code styles and php styles
This article summarizes the php good code style and shares it with you for your reference. The details are as follows:
1. Avoid using magic data
if($age<18){}
This 18 doesn't quite understand why.
You can define 28 in a variable. This variable name indicates the meaning of this value.
$ Adult_age = 18; // age of the adult's demarcation point if ($ age <$ adult_age ){}
2. function return result: Do not use a variable to store the returned result.
Once you know the returned results, you should return them immediately. This can reduce errors.
3. The function carries many parameters. No more than three
If there are many parameters, try to aggregate them into a model and pass them in. For example, an array can be used by all instances.
Why does too many parameters affect the stability of the method?
For example, modification will become very troublesome.
Now I understand. This method requires a new parameter to be passed in, so the code that originally called this method has to be changed.
Similar problems are often encountered during interface creation.
function forgot($userName, $email, $email_url, $format = 'json')
The preceding three parameters are used.
When someone calls this function,
forgot($userName, $email, $email_url, $format = 'json');
Now the requirement is changing. A new parameter is required. What should I do?
The original code will be modified. The method is unstable. Or re-open a method to meet the new requirements. Modify the caller's call code.
However, this problem can be avoided.
Make the original passed parameters into an array, as shown below:
forgot($params=array(),$format = 'json');
Aggregate into an array. This allows you to add multiple parameters.
How can we understand that the built-in functions of the php engine contain multiple parameters?
Design defects?
4. The method parameters contain Boolean parameters.
This means that this method is not a single goal. Violates a single responsibility. Added complexity.
Let's think: How can we understand the problems in our current code?