Tutorials to .com

Tutorials to .com » Php » Others » PHP development with robust code (b): effective use of variable

PHP development with robust code (b): effective use of variable

Print View , by: iSee ,Total views: 7 ,Word Count: 3430 ,Date: Mon, 20 Apr 2009 Time: 1:01 AM

"Development with php robust code" is on the settlement of large and medium-sized application of practical problems in a series of articles. In this article, PHP veteran Amol Hatwar discussed how the effective use of variables. He also demonstrated how to use PHP variable name of variable to construct the configuration file parser in order to simplify the configuration script.
In my previous article, I studied in the planning, design and even write code during a number of factors must be taken into account. In this article, you will really come into contact with the actual code, and can see the actual operation of something. If you have not read an article before, then take a look at the best now.

Correctly handle the variable
Variables and function is essential for any computer language elements. With variables, you can abstract the data; With the function, you can abstract a few lines of code. As Bruce Eckel in his book "C + + programming thinking", as said, all programming languages provide an abstract. Assembly language is a small underlying abstract machine. Then many so-called command-type language (such as Fortran, BASIC and C) is an abstract assembly language.

Abstract programming language to provide the type and quality is directly related to your best to resolve the complexity of the problem. Understanding of how to deal with PHP variables and functions, will help you effectively use them.

What in the name?
As I mentioned in the previous article, the naming convention and coding is an important agreement. No matter what you use naming conventions, please keep in mind in the project to strictly abide by it. If you are using the most widely applied naming convention, then your code will be accepted by more people.

Naming of variables, including paying particular attention to the script is being used not to cover the variable. In large-scale application, when adding new features, this is the root causes of common errors. To prevent this problem the best way is to use the prefix. Module where the variable name as a prefix to use abbreviations. For example, if a processing module to vote to have a variable saved user ID, you can name the variable $ poll_userID or $ pollUserID.

Understanding of PHP variables
PHP is a language to explain. This has many advantages, you will quickly learn to use some of them. The first advantage is obvious: it allows you save the design - code - compile - test cycle - in the editor you prepared any code can be used immediately. However, the most important advantage is that you need not worry about the type of variables in memory and how to manage these variables. All the memory allocated to the script after script after the implementation of automatic recovery by PHP. In addition, variables can perform many operations without having to know the types of variables. 1 list in the PHP code to work normally, but in c and java languages will be out a lot of error messages:

1. With variable sample PHP code

<? php
$ 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, such as to run the operation code, the code can be saved as the first one. Php files, and then the document placed in the Web server, and then point to the file browser. Better way is to install the CGI version of PHP. Then, through the shell or command prompt, enter the following command, and include your script to replace the file name script-name, so you can run the script has.

path-to-php/php script-name

The normal work of the code, because PHP is a type of loose language. Using plain English, can not consider the variable type, you can assign the string to an integer, as well as easily substitute the string with larger string smaller. This is such a language like C++ is impossible. In-house, PHP will be owned by the variable types of data and separate storage. Types stored in a separate table. When there are different types of expression that contains the time, PHP automatically determines what programmers want to do, and then change the type of table, and then automatically to the expression is evaluated.

Introduce a common minor problems
Not have to worry about the type of course very good, but sometimes it will make you into real trouble. How the case? There is a practical example: I often have the Windows-based PC to create the content to Linux systems, so that they can use them in Web. Windows-based file system in dealing with the file name is case-insensitive. File name defparser.php point DefParser.php and Windows on the same document. In the Linux operating system, they point to different files. You may promote either the whole file name with an uppercase or lowercase wide use, but the best way is to enable the case remain unchanged.

To solve this small problem
Suppose you want a function, it can not be considered in case the circumstances, given the existence of documents in a directory. First of all, the task will be broken down into a few simple steps. Decomposition of the code may sound ridiculous, but it does help when you write code to focus on this code. In addition, steps on a piece of paper has always been to rewrite the proportion is much easier to write code:

access to the source directory of all documents
Filtered. And .. directory
Check the target file exists in the directory
If the file exists, then access to sensitive documents with the correct name
If the name does not match, then return false
To read the contents of the directory, use readdir () function. In the PHP manual (see reference) of the function to obtain more details. As for now, as long as the know: readdir () every time when each call is scheduled to return to the directory name of all documents. In a list of all the file name, it return false. You will use a cycle, the cycle in the readdir () return false terminate.

But this enough? Please keep in mind, PHP is the language of the type of relaxed, which means that the integer value of 0 and false as the same (or even C also Boolean values 0 and false as equivalent). The question is not whether the code will work correctly; Imagine, if the name of the file is 0 will be the way! The script will be terminated prematurely. You can use the following script (list 2) to determine the false boolean value 0 and the equivalent of:

List 2. To identify false boolean value 0 and the script is equivalent

<? php
$ 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.

Well, you can do? PHP will you know the type of internal storage, and if access to these types of words, the problem is resolved. Boolean value false and the integer value 0 is obviously different.

PHP has a gettype () function, but let us here to choose a simpler approach. You can use the === operator (Yes, there are three equal sign). The difference is the operator of the value of comparative data at the same time and type. If you have some doubts about that, PHP still! == Operator. PHP 4 is only in these new operators and gettype () function. 3 shows a list of the complete solution to the problem code:

List 3. Integrity code

<? php
/ * 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;


Observation experience
I do not intend to list every 3 to illustrate the function of function, on the contrary, I encourage you to access PHP manual (see references). When you are not familiar with the use of the function, the assumption that the parameters and return value type is the root of another error. I do not have on the built-in PHP function to illustrate, but do not attempt to describe some things clear.

When the termination of the conditions involved in different types of variables, by using the === and! == Operator to strong type checking is very important.

Various parts of the code
I could have prepared the entire script for a function, but here I am but the code is separated into two functions. Also recall an article in the "divide and rule" the rules of it? I do so because each function is the role of different. If you use other scripts to obtain the contents of a directory, it can now achieve the easy-to-use. I hope you consider some things: Imagine the entire script as a function to achieve, and then imagine debugging, testing and reuse the code needed to work.

The proper use of recycling
Now look at the foreach cycle, think about why we did not for the cycle? Used for cycle requirements of you know the number of array - the need for an extra step. In addition, when dealing with PHP array, the array may be beyond the border. In other words, an array of 10 elements only when trying to access its first element 15. PHP does give a little warning, but as far as I know, in some cases, when running a script repeatedly, CPU activity rate suddenly rose to 100% and the continuous drop in server performance. I suggest that you avoid the use of as much as possible for recycling.

Assertion of if
Finally, I hope you look at that in get_file_list () function used to ignore. And .. directory if the conditions of the larger. Obviously, I can use traditional methods, according to check the variables constant. However, many of my own coding, I often equate missing and can not find where the next problem. Of course, PHP does not error, because it is an assignment that I was trying to not compare. When you compare the basis of constant variables and also missed out when an equal sign, PHP will be dished out an error message.

Variable variable name
Now to discuss a number of wonderful things. As a novice developer believes that the use of variable variables to complete the task is a puzzling way, so often to avoid it. In fact, it is easy to understand and use a variable variable. They have more than once helped me out, but they are an important element of the language. In fact, in some cases, the use of variable variables inevitable. Soon I will be on a reality of such, but first let us look at what is in the end the variable variable. Let us first try to make a list of 4 Code:

List 4. With variable code variable

<? php
$ myStr = "I";
$ $ myStr = "am";
$ $ $ myStr = "great.";

/ / These are new variables.
echo "$ myStr";
echo "$ I";
echo "$ am \ n";

/ / Now for the moment of truth ...";

$ am = "exaggerating.";

/ / Does it work the other way?
echo "$ myStr";
echo "$ ($ myStr)";
echo "${${$ myStr)) \ n ";

First of all, the code list of 4 statements $ myStr named variables and I assign it a string. The definition of the next statement to another variable. But this time, the name of the variable is $ myStr data. $ $ myStr tell PHP is a way to have another variable, it is meant that the "I want a variable, you can find variable $ myStr in the name of this variable." Of course, in order to achieve this, must be the definition of $ myStr. So, now you have a variable I, and am using the string value to it. The following statement to do the same thing, and great string name assigned to the variable am. And am only variable I of the data.

It clarified some things, but the echo of those strange statement in brackets is how to spend at all? That is your method of printing variable variables. If you omit the curly braces, then PHP will print when the dollar sign ($) appended to the contents of variables. They spent the first brackets tell PHP which variables to their evaluation.

Try this to consider: the variable can be done? To put it simply, they are abstract or that the data can change, and their names remain unchanged. Variable variable to do is the same thing; they are abstract data. However, in this case, the data they contain is the name of another variable.

I have 4 in the list given in the example is to allow you are familiar with variable variables. Variable variable name from the actual function of the fact: You can dynamically generate run-time variable variable name. You will construct a resolver configuration file to use this feature.

Resolver configuration file
According to my experience, in the configuration application to enable run-time, using PHP to edit the configuration file, users often complained about by. Configuration is only a list of global variables, and other applications rely on it to find the script file, URL, and other acts to control the application settings. Omission of a dollar sign, a semicolon or a period of closure of the Notes is not often undermine the entire code. What can help users?

Suppose you a file to users, allow users to use the equal sign to separate from the simple name - value pairs to edit the file. 5 is similar to the list of configuration files. # At the beginning of the line to the text of the Notes as to deal with.

List of 5. A sample configuration file

# This is sample a configuration file.
admin_fname = Amol
admin_lname = Hatwar
admin_email = amolhatwar@consultant.com
admin_login = admin
admin_pass = secretstring
# File Ends

Clearly the meaning of it? Yes, it is true ... ... Now that PHP can parse the file, why allow users to edit the configuration file it? In fact, this is very much desired. Remember, your application must be hidden to the user all the complexity at the same time, still let him know that he can control the application.

You can write a function in charge of analytical work so that you can use it anywhere without having to make any changes. Let us the task is divided into some simple steps:

To read the file line by line
No. disposed of in line # after all the elements of character
To equate for the sector, will be divided into two strings and his party, and discard equate
Remove the extra spaces in string
The corresponding variable declaration
The final step to be prepared, only the use of variable variables do. 6 shows the code list:

List 6. Analytic functions

<? php
/ * Conf_parser.php * /

/ * Give the filename with path info whenever possible. * /
function conf_parse ($ file_name) (

/ / @ In front makes the function quiet. Error messages are not printed.
$ fp = @ fopen ($ file_name, "r") or die ( "Cannot open $ file_name");

while ($ conf_line = @ fgets ($ fp, 1024)) (
$ line = ereg_replace ("#.*$", "", $ line); / / Do stripping after hashes.
if ($ line == "") continue; / / Drop blank lines resulting from the previous step.
list ($ name, $ value) = explode ('=', $ line); / / Drop '=' and split.
$ name = trim ($ name); / / Strip spaces.
$ $ name = trim ($ value); / / Define the said variable.
fclose ($ fp) or die ( "Can't close file $ file_name");

Use regular expressions to remove the #. Although the expression here is very simple, but complicated to know regular expressions will consume a large amount of CPU time. In addition, the analysis repeated for each configuration file is not a good decision-making. Better choice is: use the definition of variables or statements will be parsed the output of memory for PHP scripts. I tend to use the define () function definition, because once the value is set at run time will not be able to change it. Can find a reference to the need to be modified based on your implementation.

Concluding remarks
As it is known how effective use of variables, then you can proceed with the preparation of some of the larger procedure. In this series the next article, I will study the function and API design. At the next meeting before, I hope your happy programming!


Download def_parser.zip document, which includes the realization of the resolver configuration file, you can write a document parser to include in your script.

PHPBuilder.com visit and the Developer Shed, to get more information about the PHP variable variable name used in the sample.

Please read understand the Free Energy, this is a Web application the easy way to encode.

Download or online PHP manual.

To participate in "Writing efficient PHP" tutorial to learn how to write effective PHP code (developerWorks, 2002 years 7 months).

Please read this series of articles in the first "lay the foundation" to learn more about the design and planning elements of Web applications (developerWorks, 2002 years 8 months).

About the author
Amol Hatwar from Notepad began to contact the computer. As a GNU / Linux supporter of the absolute, he is the last program in the Microsoft platform is guilt. He is now an independent consultant to help as many companies move to GNU / Linux. As a Web application development experts in the field, he left the spare time devoted to the study no one had heard of the technology. His interests include open source software, Web services, peer-to-peer computing, and high-availability cluster. You can contact amolhatwar@consultant.com and Amol.

php other Articles

Can't Find What You're Looking For?

Rating: Not yet rated


No comments posted.