Using PHP to develop robust code two efficient use of variable _php tutorials

Source: Internet
Author: User
"Developing robust code with PHP" is a series of articles on solving real-world problems in large and medium-sized applications. In this article, PHP veteran Amol Hatwar discussed how to use variables effectively. He also demonstrated how to construct a profile parser by using variable names in PHP to simplify script configuration. In my previous article, I examined some of the factors that must be considered during planning, designing, and even writing code. In this article, you will actually be exposed to the actual code, and you can see something actually running. If you haven't read the previous article, it's a good idea to take a look at it now. Proper handling of variable variables and functions is an essential element of any computer language. With variables, you can abstract the data, and with functions, you can abstract a few lines of code. As Bruce Eckel in his book, "C + + programming ideas", all programming languages provide abstractions. Assembly language is a small abstraction of the underlying machine. Many of the subsequent so-called imperative languages (such as Fortran, BASIC, and C) are abstractions of assembly language. The kind and quality of abstraction provided by programming languages is directly related to the complexity of the problems you can solve. Understanding how PHP handles variables and functions will help you to use them effectively. What's in the name? As I mentioned in the previous article, naming conventions and coding conventions are important. Regardless of the naming convention you use, remember to strictly follow it in your project. If you use the most widely used naming convention, your code will be accepted by more people. When you name a variable, be careful not to overwrite the variable being used when you include the script. In large applications, this is a common source of error when adding new functionality. The best way to prevent this problem is to use a prefix. Use the name abbreviation of the module that contains the variable as a prefix. For example, if a module that handles voting has a variable that holds the user's identity, you can name the variable $poll _userid or $pollUserID. Understanding PHP variables PHP is an interpreted language. There are many benefits, and soon you will learn to take advantage of some of them. The first obvious benefit is that it saves you from designing-coding-compiling-testing cycles-Any code you write in the editor is immediately available. However, the most important benefit is that you don't have to worry about the types of variables and how to manage them in memory. All memory allocated to the script is automatically retracted by PHP after the script is executed. In addition, you can perform many operations on a variable without knowing the type of the variable. The code in Listing 1 works perfectly well in PHP, but throws a lot of error messages in the C and Java languages: Listing 1. Sample PHP code with variables After you install PHP, to run the running code, you can first save the code as a. PHP file, place the file on the Web server, and then point the browser to the file. A better approach is to install the CGI version of PHP. Then, you can run the script by entering the following command at the shell or command prompt and replacing script-name with the file name that contains your script. path-to-php/php script-name The code works, because PHP is a loose-type language. In easy-to-understand English, you can assign a string to an integer without taking into account the variable type, and replace the smaller string with a larger string effortlessly. This is impossible in a language like C. Internally, PHP stores the data owned by the variable separately from the type. The type is stored in a separate table. Whenever an expression with different types appears, PHP automatically determines what the programmer wants to do, changes the type in the table, and evaluates the expression automatically. Introducing a common small problem don't worry about the type is good, but sometimes that can get you into real trouble. What's going on here? Here's a practical example: I often have to move content created on a Windows-based PC to a Linux system so that it can be used on the Web. The Windows-based file system is case-insensitive when it processes filenames. File names defparser.php and defparser.php point to the same file on Windows. On the Linux operating system, they point to different files. You might advocate that the file name is either all uppercase or lowercase, but the best practice should be to keep the case intact. To solve this little problem, suppose you want a function that checks whether a given file exists in a directory without regard to case. First, break this task down into a few simple steps. Breaking down your code may sound ridiculous, but it does help you focus on this code as you write your code. Also, rewriting steps on paper is always a lot easier than writing code: Get all the filenames in the source directory filtered out. And.. Directory checks if the destination file exists in the directory if the file exists, gets the file name with the correct case if the name does not match, then returns false to read the contents of the directory, you need to use the Readdir () function. You can get more details about the function in the PHP manual (see Resources). As for now, just know: Readdir () returns the names of all the files in a given directory on each invocation. After all the file names are listed, it returns false. You will use a loop that loops in the Readdir() returns False when terminated. But is that enough? Keep in mind that PHP is a loosely typed language, which means that an integer value of 0 is considered the same as false (even C also treats 0 and Boolean false as equivalent). The question is not whether the code works properly; imagine if the name of the file is 0! The script terminates prematurely. You can use the following script (listing 2) to determine the equivalence between 0 and Boolean false: Listing 2. Script that determines whether 0 is equivalent to a Boolean value false So what can you do? You know that PHP will store the type internally, and if you can access these types, the problem will be solved. A Boolean value of false and an integer value of 0 are obviously different. PHP has a GetType () function, but let's choose a simpler method here. You can use the = = = Operator (yes, there are three equals signs). The difference is that the operator compares the values and types of the data at the same time. If you have some doubts about this, PHP also has the!== operator. These new operators and the GetType () function are only available in PHP 4. Listing 3 shows the complete code to resolve the problem: listing 3. Full code Experience gained in observation I'm not going to explain the functions of each of the functions in Listing 3, instead I encourage you to consult the PHP manual (see Resources). When you use an unfamiliar function, the assumed parameter and the type of the return value are another source of error. I'm not explaining the built-in functions in PHP, I'm going to show you something that's not too obvious. When different variable types are involved in a termination condition, it is important to use the = = = and!== operators for strong type checking. Code that consists of parts I could have written the entire script as a function, but here I split the code into two functions. Remember the rule of "divide and conquer" in the previous article? I do this precisely because each function plays a different role. If you use other scripts to get the contents of a directory, you can now use a handy implementation. I want you to consider something: Imagine implementing the entire script as a function, and then imagine the work required to debug, test, and reuse the code. Use loops correctly now look at the Foreach loop and think about why you don't need a for loop? Using a For loop requires that you know the number of items in the array-an additional step is required. Also, when working with PHP arrays, it is possible to go beyond the bounds of the array. That is, when the array has only 10 elements, an attempt is made to access its 15th element. PHP does give a small warning, but as far as I know, in some cases, when a script is run repeatedly, the CPU activity rate suddenly rises to 100% and the server performance decreases continuously. I recommend that you avoid using a for loop as much as you can. Assertion if finally, I want you to look at the one that is used in the get_file_list () function to ignore. And.. The larger if condition of the directory. Obviously, I can use the traditional method of checking variables based on constants. But in my own many coding faint strokes, I often miss the equals sign and in the future I can not find out what went wrong. Of course, PHP does not give an error because it thinks I want to assign rather than compare. When you compare constants based on variables and omit an equal sign, PHP throws an error message. Variable variable name now to discuss some wonderful things. As a novice developer, the use of mutable variables to accomplish a task is a confusing way to avoid it often. In fact, mutable 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, the use of mutable variables is unavoidable. Soon I'll look at one of these realities, but first let's see what mutable variables are. Let's first try the code in Listing 4: Listing 4. Code with mutable variables First, the code in Listing 4 declares a variable named $MYSTR and assigns the string I to it. The next statement defines another variable. But this time, the name of the variable is the data in the $MYSTR. $ $myStr is a way to tell PHP to produce another variable, which means "I want a variable that can be found in the variable $myStr." Of course, in order to do this, $MYSTR must be defined. So, now you have a variable named I and assign it a value with the string am. The next statement did the same

http://www.bkjia.com/PHPjc/531717.html www.bkjia.com true http://www.bkjia.com/PHPjc/531717.html techarticle "Developing robust code with PHP" is a series of articles on solving real-world problems in large and medium-sized applications. In this article, PHP veteran Amol Hatwar discussed how to use variables effectively. ...

  • 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.