PHP: An Easy Yet Powerful Language Syntax
August 29, 2007 Erwin Earley
This is the second in a series of articles on Zend’s PHP for i5/OS. This article presents a discussion of the syntax and features of the PHP language and sets the framework for the third article in the series, which will discuss the API toolkit. I hope you’ll look forward to the third installment, which will delve into the API toolkit that provides the ability for PHP applications to work with i5/OS features and objects. (To read the first installment in this series, go to this link.) Variables Variables in the PHP language are signified with a leading dollar sign ($). Variables in PHP are not declared but rather come into existence upon first reference. The name of a variable starts with either a letter or an underscore, and the remaining parts of a variable name can be alphanumeric characters as well as the underscore. Variable names are case-sensitive. The PHP language supports a number of variable types:
PHP determines a variable’s type at runtime based on the usage of the variable. As an example, consider the following PHP code snippet. <?php $stringnum = "30"; $integernum = "30"; if ($stringnum == $integernum) print "the values match"; else print "the values do not match"; if ($stringnum === $integernum) print "the values match"; else print "the values do not match"; ?> In the above example, the interpreter establishes the variable $stringnum as a string upon the initial reference, because the assignment value is enclosed in quotes. However, the variable $integernum is established as an integer. When the equality test is performed with the double equal sign (==), the interpreter will cast the integer value to a string and the result of the test will be TRUE (i.e., the string “the values match” will be output). The second equality test, the one with the three equal signs (===) directs the interpreter not to cast the values, therefore the string “30” will be tested against the integer 30 and the test will fail (i.e., the value “the values do not match” will be output). Arrays Arrays are the main data structure in PHP, and they are used to store related sets of data rather then using multiple variables. PHP supports several different types of arrays. An associative array is an array that maps a key to a value through name-value pairs. Associative arrays are typically used for storing information where the key describes the data. As an example: $myarray = array("first" => 1, "second" => 2, "third" => 3); $num = $myarray['first']; As you can see from the above example, the key for the array (i.e., first, second, third) directly associates with the value at that index in the array. In the above example, the variable num would be assigned the value of 1 because that is the value at the ‘first’ key in the array. Additionally, PHP supports numeric (or enumerated) arrays. Arrays of this type are based on a mapping of an index to a value. Numeric arrays are typically used for storing pieces of related information, such as lists. The following example creates an empty array and then pushes values onto the end of the array: $myarray = array(); $myarray[] = "Monday"; $myarray[] = "Tuesday"; $myarray[] = "Wednesday"; Likewise, the following example creates the array in a single step: $myarray = array("Monday", "Tuesday", "Wednesday"); It should be noted that values in enumeraged arrays can be accessed directly through the numeric index; i.e., $myarray[3] = “Wednesday” would set the value of the fourth element of the array (PHP starts counting at 0) to the string “Wednesday”. However, a numeric index will give the expected result in associative arrays because PHP would be looking for a named index of ‘3’ rather then the fourth value in the array. In addition to associative and numeric arrays, PHP also supports multi-dimensional arrays. For debug purposes, PHP provides a function (print_r) that outputs the contents of an array. The print_r function outputs the array as plain text (not HTML), and would need to be encapsulated in HTML tags if you want it output within an HTML page. The following provides a code example and the resulting output from the print_r function: PHP Code <?php $people = array("name"="Erwin","location"=>"Rochester"); print_r($people); ?> Debugger Output Array ( [name] => Erwin [location] => Rochester ) The foreach() loop is one mechanism you can use in PHP to iterate through the values in an array. As an example, the foreach() loop can be used to loop through both the keys and values of an associative array: <?php $powersof2 = array(1 => 2, 2=> 4, 3=> 8, 4 => 16); foreach($powersof2 as $exponent => $result) { echo "2 raised to the $exponent power equals $resultn"; } ?> In this example, the output would be: 2 raised to the 1 power equals 2 2 raised to the 2 power equals 4 2 raised to the 3 power equals 8 2 raised to the 4 power equals 16 In the next article, I will show you how to use the foreach() loop to process the records returned from SQL queries within PHP. Let’s finish our discussion of arrays by looking at the concept of an internal array pointer. Arrays in PHP have an internal pointer that indicates the current element in the array. The each() function returns the current key and value pair from the array. The list() function takes an array of values and assigns the values to different variables. One important distinction with regard to the internal array pointer is that the pointer is not moved back to the beginning of the array until the reset() function is called, passing the variable containing the array to be reset. As an example, consider the following code: <?php $foods = array("Steak", "Chicken", "Potatoes", "Pork"); while (list($index, $food) = each($foods)) { echo "I like eating $foodn"; } $foods[] = "Corn"; while (list($index, $food) = each($foods)) { echo "I also like eating $foodn"; } ?> This code will result in the following output: I like eating Steak I like eating Chicken I like eating Potatoes I like eating Pork I also like eating Corn The value of “Corn” is pushed onto the end of the array. The second while loop only processes the last array element because the internal array pointer was not reset after the first while loop. Loops, Control Statements, and Logical Operators PHP supports the standard looping constructs that one would expect a computer language to support. These include the for, while, and do-while loops as well as the foreach loop that we looked at previously. PHP also supports the if, if-else, and if-else-if-else control constructs. You can combine multiple tests with logical operators. Logical operators in PHP examine the operand(s) and return a single value:
Let’s take a look at one of the control structures and logical operators in a code example: <? $magazine = "IT Jungle"; $author = "Erwin Earley"; if (strtoupper($magazine) == "IT JUNGLE" && strtoupper($author) == "ERWIN EARLEY") echo "You must be reading a PHP article"; else if (strtoupper($magazine) == "IT JUNGLE" echo "You must be reading an article from IT Jungle"; else echo "Why aren't you reading IT Jungle"; ?> In the above example you can see that we use the and logical operator (&&) to combine both the test of the $magazine value as well as the $author value. Also note that we were able to use a function (strtoupper) in place of a variable or value. The function will execute and return the value in place and the value returned will then be used in the test. Comments As we all know, well commented code is key to the maintainability of that code. PHP supports several different comment standards. Single-line comments are denoted with either two slashes (//) or the hash symbol (#), and they do not have to start at the beginning of a line: $1 - 0; // Counter for the loop $balance = 500; # Initial account balance Multi-line comments are started with the /* character combination and end with the */ character combination: /* ****************************** * You can get fancy with these * * ******************************/ Functions You can use functions to accomplish any number of separate tasks. Functions receive a series of parameters and return a result. The PHP language itself consists of a large number of functions. As an example, the strtoupper function capitalizes lowercase letters. echo "strtoupper("IT Jungle"); // IT JUNGLE As the above example shows, you can use a function almost anywhere that a variable or string would normally appear in the PHP code. PHP will execute the function and replace it with the return value. One interesting aspect of PHP is that a function can change the value of a variable by assignment of the return value to the variable. Consider the following code example: $magazine = "IT Jungle"; $magazine = strtoupper($magazine); echo $magazine; // IT JUNGLE Documentation for the PHP built-in functions is available online at this link. As an example, to display the syntax manual page for the strtoupper function enter the following URL: http://php.net/strtoupper. This page displays the syntax of the function as well as code examples. In addition to the built-in functions provided by PHP, you can also develop your own customized functions within our PHP code. The use of customized functions can help to make larger applications easier to develop and maintain, since different tasks can be allocated to different functions. Here is an example of how to code a customized function: function x5($number) { return ($number * 5); } echo x5(10); // 50 The above code defines a function called x5 that takes a single argument (referred to as $number). The function returns the argument multiplied by 5. Functions can have both required and optional parameters. The optional parameters have to be defined after the required parameters. A parameter is made optional by assigning a default value to the parameter in the function definition. Consider the following example: function optionalDemo($greeting, $count = 1); { for ($i = 0; $i < $count; $i++) { echo $greeting . "n"; } } optionalDemo("Hello"); optionalDemo("good Bye", 2); In the above example the function optionalDemo is declared with two arguments: a required argument referenced as $greeting and an optional argument referenced as $count. The optional argument is used to indicate the number of times that the passed greeting should be output. Notice the two calls to the function. In the first call only a single argument is passed, therefore the default value will be assigned to the $count parameter and the greeting will be output a single time. In the second call, both the greeting and count arguments are passed, causing the greeting to be output twice. Variables declared inside of a function are local (or scoped) to that function. This is probably best explained with an example: function scopedemo($fruit) { $fruit = 20; } $fruit = 10; scopedemo(fruit); echo $fruit; // 10 Notice in the above example that outside of the function a variable called $fruit is assigned a value of 10. Inside the function a variable called fruit is assigned a value of 20. However, when the variable is referenced outside of the function, it will again have the assigned value of 10. Put another way, there are two variables with the name of $fruit–one that is scoped to the scopedemo function and one that is scoped outside of the function. Object Oriented Programming (OOP) Let’s finish our discussion of basic PHP syntax with a look at the support provided by PHP for Object Oriented Programming (OOP). As we have seen, arrays allow us to group related data together and functions allow us to group related code together. Objects allow us to group related code and data together. OOP provides methods for making it easier to handle complex data structures in larger coding projects. When looking at OOP there are a number of terms that need to be understood:
Let’s take a look at a code example: <?php class car { public $make; private $model; function _construct($make, $model) { $this->make = $make; $this->model = $model; } function printMake() { echo $this->make . "n"; } } $camaro = new car("chevrolet", "Camaro"); $camaro->printMake(); $mustang = new car("ford", "mustang"); $mustang->printMake(); ?> There are number of items to make note of in the above example:
Powerful, Yet Easy to Learn! I hope this article has aroused your interest in PHP. I encourage you to explore PHP more fully through myriad available resources and documentation. Some resources you might want to take a look at would include:
A little reading, and you’ll be prepared for next time, when we’ll dig into the API toolkit. Erwin Earley is an Advisory Software Engineer in the IBM lab located in Rochester, Minnesota, and heads up the Open Source Technologies Center of Competency for System i within the System i Technology Center. At that center, he provides education and enablement services for open source related technologies on System i including Linux , MySQL, and Zend’s PHP. Earley currently holds certifications from Red Hat as well as the Linux Professional Institute and is a candidate for the certification with Zend’s PHP. RELATED ARTICLE PHP on i5/OS: A Whole New Stack
|