Structured and Reusable Code

I l @ ve RuBoard

My first experience with programming was in college. My teacher was Chris Pickford, and he was one of the most patient people I have ever met. Chris did his best to teach my class of novice but very keen programmers the concepts and benefits of structuring and reusing our code. It was only when I programmed for a living that I was thankful for what Chris taught me. This section is for you, Chris.

Structured and reusable code allows you to break your code into ordered pieces so that you can effectively and efficiently reuse pieces of your code within your application. It makes sense to do this, because your application might do certain things repeatedly, such as connect to a database, query a database, and display the database data. By breaking your application into pieces, you reduce the number of errors that might occur and reduce the amount of time it takes you to write an application (and saving time is always a good thing). PHP lets you break up code using several methods , functions, classes, and includes.

Using Functions

Functions are one of the easiest methods of breaking code into reusable pieces.

 <?php  function HelloName($namearg) { return "Hello " . $namearg;  }  $phrase = HelloName("Andrew");  print("$phrase");  ?> 

This code creates a function that displays a message. You pass a name to the function, and it uses that name to display a message. First, you must create the function:

 function HelloName($namearg) { return "Hello " . $namearg;  } 

Note that you send the result of calling this function using the following:

 return "Hello " . $namearg; 

In other words, the return statement sends back a result when the function is called. Therefore, to accept the result of the function, you must store the result as you call the function:

 $phrase = HelloName("Andrew"); 

Finally, you display the function's result:

 print("$phrase"); 

If you run the script, you can see the result of the function call.

Passing Data by Reference or by Value

Functions also let you modify the data you pass to them. Used in this context, you can either keep the data unchanged when it returns from the function (called passing by value ) or change the data (called passing by reference ).

 <?php  function WhoIsCool($namearg) { $namearg .= ' are cool';  }  $name = "PHP programmers";  //by value  WhoIsCool($name);  print("$name");  //break lines  print("<BR>");  //by reference  WhoIsCool(&$name);  print("$name");  ?> 

This code modifies a string variable called $name . You first apply some data to the variable:

 $name = "PHP programmers"; 

The function you use appends a string of data to the string variable you pass to the function:

 function WhoIsCool($namearg) { $namearg .= ' are cool';  } 

Next you call the function by value and display the result. Note that PHP does this by default.

 WhoIsCool($name);  print("$name"); 

You then call the function by reference and display the result:

 WhoIsCool(&$name);  print("$name"); 

To call the function by reference, you append an ampersand ( & ) to the start of any data you pass to the function (such as &$name ). If you run the script, you can see that when you call by value, the string variable is not changed by the function (see Figure 3.18). However, when you call by reference, the value is changed.

Figure 3.18. The result of passing by value and by reference.

graphics/03fig18.gif

Using Objects

PHP lets you extend and reuse your code in the form of objects. PHP objects let you break code into reusable segments, which PHP calls classes . This takes code structuring and reuse one step further from functions, because it lets you completely separate the different parts of an application. In other words, a class can hold its own variables and functions. By separating the code in this way, you can be sure that when you maintain and debug a segment of code, all the code you need to look at is held within that class. So how do you use objects in PHP?

 <?php  class myclass {        function HelloName($namearg) { return "Hello " . $namearg;       }  }  //create new instance of class  $myobject = new myclass();  //call HelloName function of class and store result  $phrase = $myobject->HelloName("Andrew");  //display result  print("$phrase");  ?> 

First, you need to define a PHP class to create your object:

 class myclass {      function HelloName($namearg) {      return "Hello " . $namearg;       }  } 

A couple things are worth noting. First, all code in a class is held within the brackets of a class function. Second, note that the HelloName function from earlier in the chapter reappears here. You don't strictly need to contain your functions within a class, but it makes sense to do so when structuring your code. As before, the HelloName function accepts a variable as an argument, appends some data to the variable, and returns the variable as a result.

 $myobject = new myclass(); 

In the rest of the PHP code, you can make use of the object. To do this, you must first create an instance of the object and store it in a variable. Why do this? This step is yet another method of code reuse. You can use the same object repeatedly to take different data and obtain different results. You can't reuse the object at the same time though, so you must create a different mirror image of the object each time you use it. In this example, you use the object only once, but the syntax rules remain the same. PHP provides you with the new function for creating mirror images of objects. You store the mirror image of the object in the variable $myobject :

 $phrase = $myobject->HelloName("Andrew"); 

Now you can use the object. PHP breaks this down into the following:

ObjectInstance -> FunctionName

In the example, you are calling the HelloName function of the myclass object. If you run the script, you can see the result of calling the function within the object. This example is quite simple. To show what other objects in PHP can do, we must build on it:

 <?php  class myclass {      var $nametoshow = "Everyone";       function AddName($namearg) { $this->nametoshow = $namearg;       }       function HelloName() {      return "Hello " . $this->nametoshow;       }  }  //create first instance of class  $myobject1 = new myclass();  //call HelloName function of class and store result  $phrase = $myobject1->HelloName();  //display result  print("$phrase");  print("<BR>");  //create second instance of class  $myobject2 = new myclass();  $myobject2->AddName("Andrew");  $phrase = $myobject2->HelloName();  //display result  print("$phrase");  ?> 

The class is made up of several things:

 class myclass {      var $nametoshow = "Everyone";       function AddName($namearg) { $this->nametoshow = $namearg;       }       function HelloName() {      return "Hello " . $this->nametoshow;       }  } 

First, the class has a variable within it. Remember that this variable is available only to code within the class and thus is called a class variable.

 var $nametoshow = "Everyone"; 

Note that you must declare the class variable using the var statement. This is so that PHP knows what is a variable and what is a function (called declare code ).

Next, the object has two functions:

 function AddName($namearg) { $this->nametoshow = $namearg;  }  function HelloName() {      return "Hello " . $this->nametoshow;  } 

The first function takes a variable as an argument and sets a class variable to the value of that argument:

 function AddName($namearg) { $this->nametoshow = $namearg;  } 

Note the PHP syntax for setting class variables:

 $this->nametoshow = $namearg; 

This code line refers to the nametoshow variable within the current class. This syntax is used so that you can be sure that the variable is indeed a class variable and that PHP won't confuse it with another variable outside the class. Note that you can only set class variables in this manner with a function; as before, PHP expects declared code outside a function.

 function HelloName() {      return "Hello " . $this->nametoshow;  } 

The second function returns the class variable to code outside the class. The code to call on your class does two things. First, it creates an instance of the class and shows the result of the class variable:

 $myobject1 = new myclass();  $phrase = $myobject1->HelloName();  print("$phrase"); 

Next, it creates another instance of the class and passes a value to the AddName function, so the class variable takes that value. It then displays the new class variable value:

 $myobject2 = new myclass();  $myobject2->AddName("Andrew");  $phrase = $myobject2->HelloName();  print("$phrase"); 

If you run the script, you can see that the value of the class variable is unchanged and also see the new value of the class variable, as shown in Figure 3.19.

Figure 3.19. Changing the value of a class variable.

graphics/03fig19.gif

I l @ ve RuBoard


PHP Programming for Windows
PHP Programming for Windows (Landmark (New Riders))
ISBN: 0735711690
EAN: 2147483647
Year: 2002
Pages: 99

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net