PHP tips on how to cleverly avoid some bad code in PHP programs

Source: Internet
Author: User
Tags php language
This article is to share with you how to find the bad code in PHP instance code and how to fix the problem, interested in the friend reference.

PHP development has been almost a year, in this year's time, learning a lot of production environment skills, learning a lot of things, during the period also read some excellent source code and about the book, to write code this piece has a certain thinking, but also read a lot of others write good code and bad Code, Here to talk about your own feelings and improve it.

This blog to speak frankly their own sentiment, in writing code, I gave myself the rules, so that the code can be clearly readable and less to go some pits. While these simple rules are not as exciting as design patterns, the usual attention can make the code look refreshing.

1. Do not use undeclared variables outside of objects

The problem may not be easily understood. This problem is determined by the characteristics of the PHP language itself. Because PHP is a weak type of dynamic scripting language, in many cases, given the language of the province very loose conditions for developers to write code. But often these conveniences also turn into pits, so it is especially important to note that when using some dynamic languages it is convenient to use the notation.

Here we first declare a class, call this class for the user class, the background of the users class is set to, the frame comes with, not allowed to modify, and hidden in the framework, not easy to find, the actual case can refer to the Laravel Framework request class, the code is as follows:

Class User {public  $username;  public $password;    Public $otherInfo = [];      Public Function Readuserinfo () {    return [      ' username ' = = $this->username,      ' password ' = $this Password,    ];  }    Public Function Addatri ($info) {    Array_push ($this->otherinfo, $info);}  }

This kind of code looks like a treat, but next, we need to manipulate this class:

$user = new User (); $user->userrealname = "Hello World";

Such code is fully operational in PHP and does not give an error, but the code will interfere with some of the things that follow. We now assume that the above code is an interceptor in a PHP Web project, or middleware, and then we will use an instance of this class in the controller, and use the variable added to this middleware, as follows:

Class Weboperate {public   function dooprate (User $user) {     $user->userrealname = ' Hello World ';     Next ($user);   } }

The scenario set here is that Weboperate is a middleware, all controllers will go to this middleware after the controller, after processing the corresponding controller function, next, the controller will inject the instance of the middleware in For use by the controller, and middleware developers are not very concerned about its existence:

Class Indexcontroller {public   function index (User $user) {     return $user->userrealname;   }}

And this code can be perfectly run, next, the developer wants the real another user class, this user class to add some other functions, as previously said, this class is deep in the framework and difficult to find, and does not allow the modification, because the other features use this class, so we only inherit and add methods. Based on the development experience, the developer will assume that the Userrealname variable exists in the user class, so this is how it is written:

The first is based on the user-derived teacher class:

Class Teacher extends User {public   function SayHello () {     return ' Hello World ';   }}

In this way, our teacher can be sayhello, but, at this time, in our controller also want to know the teacher's real name, how to do? Based on experience, we can replace injected classes with teacher and return real names:

Class Indexcontroller {public   function index (Teacher $user) {     return $user->userrealname;   }}

Then this problem comes, in fact, the user class does not have this class, so this variable has no value, but according to experience, is the middleware has been assigned a value once, so we should be able to use directly, but there is no such value, we began to see the source code found that the inherited user class does not exist in this variable, So why is this variable used before, because in the middleware, the user's strength is paid value.

So we can't just use undeclared variables directly in a class.

We should write this:

Class Weboperate {public  function dooprate (User $user) {    $user->addatri ([      ' userrealname ' = ' hello ') World ',    ]);    Next ($user);}  }

Such middleware, in the invocation of the inheriting class can also use the same method, very simple and very difficult to appear bad taste.

2. Class or array

In fact, this problem also derived from another problem, is the function return value of the problem.

First of all, I made it clear that a function to do many types of return values is my personal feeling is not good, although in dynamic language is very common, many PHP native methods have this, but, in the production of this way will cause the uncertainty of function return, we need to make a lot of judgments to prove our conclusion, but, If the return value type is only one, then we can directly judge the return value just fine.

Just like the following code:

Public Function Addnewuser () {    $res = $this->adddata ();    if ($res) {      return true;    } else {      return [        ' ERROR ' = 1,        ' errormsg ' = ' = ' did not add success '      ];    }  }

Such code is often judged as a caller more than once, as follows:

Public Function Index () {    $res = $this->addnewuser ();    if (Is_array ($res) && isset ($res [' ERROR ']) {      return isset ($res [' errormsg '])? $res [' ErrorMsg ']: "Unknown error"; c13/>}    return "Success";  }

Such code almost every call to complete this function will have this set of appearance, not only the code is not beautiful, and very bloated.

Such code needs to be improved by limiting the return value of the function first. For example, we only let this function return a number of type bool:

Public Function Addnewuser () {  $res = $this->adddata ();  if ($res) {    return true;  } else {    return false;}  }

But, obviously, most of the time, we want to be not simple true value, so we will choose to return more information, at this time, we can have three ways to deal with.

1) Returns the number of type int, and then through the number of the int type to judge the processing result, we can add the mapping relationship:

Class operate{public  $operateRes = [    0 = ' success ',    1 = ' Add failed ',    2 = ' Unknown error ',  ];      Public Function Addnewuser () {    $res = $this->adddata ();    if ($res) {      return 0;    } else if ($res > 1) {      return 1;    }    return 2;  }  }

The caller of this method can simply use the method and give a hint:

$opera = new Operate (), $res = $opera->addnewuser (); return $opera->operateres[$res];

When you give a uniform return value type, you do not need to judge the return value type at all, and you can set a canonical return hint.

2) We can also use arrays

3) The array is not lack of qualitative, because many times, the array can be considered less write some elements, if less write, the program directly error, very bad.

So the third way is to suggest the return of a fixed format, written as a class, to return, using this class:

Class operate{public  function Addnewuser () {    $res = $this->adddata ();    $result = new result ();    if ($res) {      $result->errno = 0;      $result->errmsg = "Success";    } else if ($res > 1) {      $result->errno = 1;      $result->errmsg = "Failed";    }    $result->errno = 2;    $result->errmsg = "Unknown error";    return $result;  }  } Class Result {public  $errno;  public $errmsg;}

This return guarantees the existence of all variables, as well as the ability to reduce one judgement at a time.

So, combined above, when we return the results, try to use the same type of variables, minimize the use of array return.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.