Develop robust code with PHP: effectively use variables
Source: Internet
Author: User
Article title: develop robust code with PHP: effectively use variables. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
Correct variable processing Variables and functions are essential to any computer language. With variables, you can abstract data. with functions, you can abstract several lines of code. As Bruce Eckel said in his book C ++ programming ideas, all programming languages provide abstraction. Assembly language is a small abstraction of the underlying machine. Many of the following so-called imperative languages (such as Fortran, BASIC, and C) are abstract assembly languages.
The types and quality of abstraction provided by programming languages are directly related to the complexity of the problems you can solve. Understanding how PHP processes variables and functions will help you use them effectively.
What is in the name? As I mentioned in the previous article, naming conventions and coding conventions are important. No matter what naming conventions you use, remember to strictly abide by them in the project. If you use the most widely used naming conventions, your code will be accepted by more people.
When naming variables, pay special attention not to overwrite the variables in use when including scripts. This is the root cause of common errors when new features are added to large applications. The best way to prevent this problem is to use a prefix. Use the abbreviated name of the module where the variable is located as the prefix. For example, if a module for voting processing contains a variable that saves the user ID, you can name the variable $ poll_userID or $ pollUserID.
Understanding PHP variables PHP is an interpreted language. This has many benefits, and soon you will learn to use some of them. The first obvious benefit is that it saves you the design-encoding-compilation-test cycle-any code you write in the editor is ready for use immediately. However, the most important benefit is that you don't have to worry about the variable type and how to manage these variables in memory. All scripts allocated to the script are automatically withdrawn by PHP after the script is executed. In addition, you can perform many operations on the variable without having to know the type of the variable. The code in listing 1 works normally in PHP, but a lot of error messages are thrown in C and Java:
Listing 1. Sample PHP code with variables
$ MyStr = 789696; // An integer.
$ MyVar = 2; // Another integer.
$ MyStr = "This is my favorite band:"; // Strings are more fun.
$ MyStr = $ myStr. "U". $ myVar; // Doing this is OK, too.
Echo "$ myVar \ n ";
?>
After installing PHP, if you want to run the code, you can first save the code as a. php file, then place the file on the Web server, and then point the browser to the file. A better solution is to install the CGI version of PHP. Then, enter the following command in a shell or command prompt and replace script-name with the file name containing your script to run the script.
Path-to-php/php script-name
This code works properly because PHP is a loose language. In easy-to-understand English, you can assign strings to integers without considering the variable type, and replace smaller strings with larger strings effortlessly. This is impossible in a language like C. Internally, PHP stores the data and types of variables separately. Type is stored in a separate table. Whenever an expression contains different types, PHP automatically determines what the programmer wants to do, changes the type in the table, and automatically evaluates the expression.
This section describes a common small problem. There is no need to worry about the type, but sometimes it will make you into real trouble. What's going on? Here is an actual example: I often have to move the content created on a Windows-based PC to a Linux system so that they can be used on the Web. Windows-based file systems are case insensitive when processing file names. The file names DefParser. php and defparser. php point to the same file on Windows. In Linux, they point to different files. You may recommend that the file name be either in uppercase or lowercase, but the best practice is to keep the case unchanged.
Solve this small problem Suppose you want a function that can check whether a given file exists in a directory without case sensitivity. First, the task is divided into some simple steps. Code decomposition may sound a bit ridiculous, but it does help you focus on this code when writing it. In addition, rewriting steps on paper are always much easier to write code:
Retrieve all file names in the source directory
Filter out the. and. directories
Check whether the target file exists in this directory.
If the file exists, obtain the file name with the correct case
If the name does not match, false is returned.
To read the contents of a directory, you must use the readdir () function. You can get more details about the function in the PHP Manual (see references. As for the time being, as long as you know: readdir () will return the names of all files in the given directory one by one during each call. After listing all the file names, it returns false. You will use a loop that terminates when readdir () returns false.
But is that enough? Keep in mind that PHP is a loose language, which means that the values of integer 0 and false are treated as the same (even C regards 0 and Boolean false as the equivalent ). The problem is not whether the code works normally. imagine what if the file name is 0! The script will be terminated too early. You can use the following script (listing 2) to determine the equivalence between 0 and boolean value false:
Listing 2. scripts that determine whether 0 is equivalent to Boolean false
$ File_name = 0;
If (0 = $ file_name ){
Echo "The code is in trouble... \ n"; // This text prints on the screen.
}
Else {
Echo "Phew... The code is safe"; // This text never prints.
}
?>
So what can you do? You know that PHP will store types internally, and if you can access these types, the problem will be solved. The Boolean value false is significantly different from the integer value 0.
PHP has a gettype () function, but let's select a simpler method here. You can use the ===operator (yes, there are three equal signs ). The difference is that this operator compares the values and types of data at the same time. If you are confused about this, PHP still has it! = Operator. Only PHP 4 has these new operators and gettype () functions. Listing 3 shows the complete code to solve the problem:
Listing 3. complete code
/* This is the function where the action takes place */
Function chk_file_name ($ name, $ path = "."){
$ FileList = get_file_list ($ path );
Foreach ($ fileList as $ file ){
If (eregi ($ name, $ file )){
Return $ file;
}
}
Return false;
}
/* Return the list of files in a given directory in an array.
Uses the current directory as default .*/
Function get_file_list ($ dirName = "."){
$ List = array ();
$ Handle = opendir ($ dirName );
While (false! ==( $ File = readdir ($ handle ))){
/* Omit the '.' and the '..' directories .*/
If (".." = $ file) | ("." = $ file) continue;
Array_push ($ list, $ file );
}
Closedir ($ handle );
Return $ list;
}
?>
Observed experience I do not intend to describe the functions of each function in listing 3. Instead, I encourage you to read the PHP Manual (see references ). When you use an unfamiliar function, the type of the parameter and return value is another error source. I did not describe the built-in functions in PHP, but intended to describe something that is not very clear at a glance.
When different variable types are involved in the termination condition, use = and! = It is very important to perform a strong type check for operators.
Code composed of various parts I could have compiled the entire script into a function, but here I split the code into two functions. Do you still remember the rule "divide and conquer" in the previous article? I am doing this because each function plays a different role. If you use other scripts to obtain the content of a directory, you can now use it easily. I want you to consider some things: imagine implementing the entire script as a function, and then imagining the work required to debug, test, and reuse code.
Correct use of loops Now let's take a look at the foreach loop. why not use the for loop? Using the for loop requires you to know the number of items in the array-an additional step is required. In addition, PHP arrays may be processed beyond the array boundary. That is to say, when the array has only 10 elements, it tries to access its 15th elements. PHP does give a small warning, but as far as I know, in some cases, when a script is repeatedly run, the CPU activity rate suddenly increases to 100%, and the server performance drops continuously. We recommend that you avoid using the for loop whenever possible.
Assertion if Finally, I want you to study the large if condition used in the get_file_list () function to ignore the large if conditions in the... directory. Obviously, I can use a traditional method to check variables based on constants. However, in many of my own code tricks, I often miss the equal sign and cannot find any problem in the future. Of course, PHP will not report an error because it thinks that I want to assign a value rather than compare it. When you compare constants based on variables and omit an equal sign, PHP will throw an error message.
Variable name Now let's discuss some wonderful things. As a novice developer, it is confusing to use variable variables to complete a task, so it is often avoided. In fact, variable variables are easy to understand and use. They have helped me out of trouble more than once, and they are an important language element. In fact, in some cases, it is inevitable to use variable variables. Soon I'll look at this kind of reality, but first let's see what the variable is. Let's first try the code in listing 4:
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