PHP is a language that was designed to be easily embedded into HTML pages (although you don't have to do it that way). Most PHP pages have PHP code and HTML intermixed. When a Web server reads a PHP page, it is looking for two things to let it know it should start reading the page as PHP rather than HTML, the start and end PHP tags: , respectively.
If you have configured your php.ini file to accept "short tags" (which are enabled by default), then you can use the syntax instead. Additionally, you can configure your php.ini file so that it accepts ASP style tags, <% and %>. This feature is turned off by default, and its only real purpose seems to be to allow certain HTML editors to recognize the in-between code as something other than HTML, in which case the editor won't mangle the code by imposing its own set of HTML syntax rules upon the code.
A brief example of PHP embedded in HTML:
Welcome To The Web Site Of !
The code above, when viewed via a Web server, simply prints out the name of the company in place of the PHP code.
In general, individual lines of PHP code should end with a semicolon, although it is not necessary to use semicolons if a beginning or an ending bracket is used (this will make sense when you look at if/then statements).
For example:
echo "a line of code";
echo "another line of code;
?>
Variables
You can also easily intertwine small segments of PHP into HTML, such as when printing out the value of a variable:
Today's Date is .
The "
You can include comments in your PHP scripts. Comments are ignored by the Web server, and any comments contained within the PHP code are not sent to a browser. There are three forms of comments:
-
#— Used just like it is used in PERL; comments out the remainder of the line after the # symbol.
-
//— Used just like it is in JavaScript; comments out the remainder of the line after the // symbols.
-
/* and */— Comments out anything in between the two sets of symbols. This is the same syntax used in C to comment code.
Examples of comments in PHP code:
You will most often see comments denoted using the // characters or the /* and */ characters. The # character is rarely seen, although it is still valid.
Variables in PHP are denoted by the "$". To assign the value "Hello World" to the variable $a, you simply call it in your code:
$a = "Hello World";Strings must be enclosed by quotes, but they can contain variables themselves:
$a = 4; $string = "The value of a is $a"; // $string = "The Value of a is 4";PHP variables do not have to be declared ahead of time, nor do they require a type definition. Note that you may get a warning about using undeclared variables if you try to use them before giving them a value (depending on how you set up error reporting in php.ini, see Chapter 8). For example:
$a = 4; $c = $a + $b; // $c = 4, but a warning appears "Warning: Undefined variable..".Warnings do not stop a script from continuing. If you forgot to add a semicolon at the end of one of the lines, then you would get a Parser error, which prohibits the script from running.
Since PHP variables are not typed, you don't have to worry about performing mathematical equations on the wrong type, as you might in C. For example:
$a = 4; $b = "5"; $c = $a + $b; // $c = 9;PHP also supports boolean variables, which can be assigned either a one or a zero, or the words true or false:
$a = true; $b = 1; //$a = $b $c = false; $d = 0; //$c = $dOperators
PHP support for operators includes the following:
Arithmetic Operators
PHP supports the standard mathematical operators:
$a = 4;
$b = 2;
//Addition: $a + b = 6
//Subtraction: $a - $b = 2
//Multiplication: $a * $b = 8
//Division :$a / $b = 2
//Modulus (remainder of $a / $b): $a % $b = 0
//Increment: $a++ (would equal 5 since $a = 4)
Assignment Operators
The two main assignment operators in php are "=" and ".". The equals sign should be obvious; it assigns a value to a variable:
$a = 4;
$b = $a;
// $b = 4
Comparison Operators
PHP supports the standard comparison operators, as shown in Table 1-1:
OPERATOR | DESCRIPTION |
---|---|
$a == $b | test if two values are equal |
$a != $b | test if two values are not equal |
$a < $b | test if the first value is less than the second |
$a > $b | test if the first value is greater than the second |
$a <= $b | test if the first value is less than or equal to the second |
$a >= $b | test if the first value is greater than or equal to the second |
PHP also supports the standard increment and decrement operators:
$a = 5;
$a++;
// $a = 6
$b = 5;
$b--;
//$b = 4
Concatenating Strings
The "." operator concatenates two values:
$sentence_a = "The quick brown ";
$sentence_b = "fox jumped...";
$sentence_c = $a . $b;
//$sentence_c = "The quick brown fox jumped...";
Arrays
PHP supports both numerical arrays (array items are indexed by their numerical order) as well as associative arrays (array items are indexed by named keys).
$a = array(1, 2, 3, 4);
//$a[0] = 1
//$a[1] = 2
//$a[2] = 3
//$a[3] = 4
$b = array("name"=>"Fred", "age" => 30);
//$b['name'] = "Fred"
//$b['age'] = 30
If/Then Statements
One of the most common PHP language constructs that you will encounter is the if/then statement. The if/then statement allows you to evaluate an expression and then, depending if it is true or not, take a course of action. For example:
$a = 1; if($a) { echo "True!"; }Since $a = 1, then PHP interprets it in the context of the if statement to be a boolean type. Since 1 = true, the if statements prints out the message. Literally you can read it as "If True, then print out "True!".
Another example, but this time with an "else" clause:
$a = 5; $b = "10"; if($a > $b) { echo "$a is greater than $b"; } else { echo "$a is not greater than $b"; }PHP doesn't care that $a is an integer and $b is a string. It recognizes that $b also makes a pretty good integer as well. It then evaluates the expression, "If $a is greater than $b then print out that $a is greater than $b; if not (else) then print out $a is not greater than $b." It's also important to note that you don't say, "$a is less than $b," since it is possible that $a could be equal to $b. If that is the case, then the second part of the expression, the else statement, is the part that runs.
Note the use of brackets to enclose the actions. Also note the lack of semicolons where the brackets are used.
One final example is the if/elseif/else statement:
if($a == $b) {// do something
} elseif ($a > $b) {
// do something else
} elseif($a < $b) {
// do yet something else
} else {
// if nothing else we do this...
}
Switch Statements
In the C programming language, switch statement support arose out of the need for a little something extra when doing if/then types of computation. With the if/then statement, you are locked into a single condition. Switch statements allow for additional evaluations of the data, even though one of the cases may have been met. Switch statements can also save you from typing many if/elseif/elseif/… statements. PHP follows C's use of switch statements.
$a = "100";
switch($a) {
case(10):
echo "The value is 10";
break;
case (100):
echo "The value is 100
";
case (1000):
echo "The value is 1000";
break;
default:
echo "Are you sure you entered a number?";
}
As you can see, switch statements have four basic parts:
-
The switch— The switch identifies what value or expression is going to be evaluated in each of the cases. In the example above, you tell the switch statement that you are going to evaluate the variable $a in the subsequent cases.
-
The case— The case statement evaluates the variable you passed from the switch command. You can use case() the same way you'd use an if statement. If the case holds true, then everything after the case statement is executed, until the parser encounters a break command, at which point execution stops and the switch is exited.
-
Breakpoints— Defined by the break command, exit the parser from the switch. Breakpoints are normally put after statements executed when a case() is met.
-
Default— The default is a special kind of case. It is executed if none of the other case statements in the switch have been executed.
For Loops
For loops are useful constructions to loop through a finite set of data, such as data in an array:
for($i = 0; $i < sizeof($array); $i++) {
//do something with array[$i];
}
For loops require three things when they are defined:
-
Counter— In the above example, $i = 0. You can pass in an already assigned variable or assign a value to the variable in the for statement.
-
The condition required to continue the for loop— In the above example, while $i is less than the size of the $array, the for loop continues to be executed.
-
Statement to modify the counter on each pass of the loop— In the above example, $i++ increments the counter after each loop.
Foreach Loops
Foreach loops allow you to quickly traverse through an array.
$array = array("name" => "Jet", "occupation" => "Bounty Hunter" );
foreach ($array as $val) {
echo "$val";
}
Prints out:Jet
Bounty Hunter
You can also use foreach loops to get the key of the values in the array:
foreach ($array as $key => $val) {
echo "$key : $val";
}
Prints out:name : Jet
occupation : Bounty Hunter
While Loops
While loops are another useful construct to loop through data. While loops continue to loop until the expression in the while loop evaluates to false. A common use of the while loop is to return the rows in an array from a result set. The while loop continues to execute until all of the rows have been returned from the result set:
while($row = mysql_fetch_array($result)) {
// do something with the resulting row
}
You can also use the continue command to skip over the current iteration of the loop, then continue. For example:
while($row = mysql_fetch_array($result)) {
if($row['name'] ! = "Jet")) {
continue;
} else {
// do something with the row
}
Do While Loops
Do while loops are another useful loop construct. Do while loops work exactly the same as normal while loops, except that the script evaluates the while expression after the loop has completed, instead of before the loop executes, as in a normal while loop.
The important difference between a do while loop and a normal while loop is that a do while loop is always executed at least once. A normal while loop may not be executed at all, depending on the expression. The following do while loop is executed one time, printing out $i to the screen:
$i = 0; do { print $i; } while ($i>0);Whereas the following is not executed at all:
$i = 0; while($i > 0) { print $i; }Quite frankly, I never find much use for do while loops, but you may find an odd problem that requires it.
User-Defined FunctionsIn addition to PHP's built-in functions, you can create your own functions. Remember that if you want to use variables that exist outside of the function, then you must declare them as global variables or assign them as arguments to the function itself.
function check_age($age) {
if ($age > 21) {
return 1;
} else {
return 0;
}
}
//usage:
if(check_age($age)) {
echo "You may enter!";
} else {
echo "Access Not Allowed!";
exit;
}
The function would be called from within your script at the appropriate time, using the following syntax:
$age = 10;
check_age($age);
// prints "Access Not Allowed!" to the screen
Object Oriented Programming with PHP
PHP supports Object Oriented Programming (OOP) in the form of classes. Just like in other OOP languages, the classes can be extended for greater reuse of code.
To create an address entry class that contains a person's first and last name and phone number:
class address_book_entry {var $first;
var $last;
var $number;
function set_name($first, $last) {
$this->first = $first;
$this->last = $last;
}
function set_number($number) {
$this->number = $number;
}
function display_entry() {
echo "
Name: " . $this->first . " " . $this->last;
echo "
Number: " . $this->number;
}
} //Usage:
$entry = &new address_book_entry;
$entry->set_name("Muhammad Faisal ","Jawaid");
$entry->set_number("555-555-5555");
$entry->display_entry();
//displays: Name: Muhammad Faisal Jawaid Number: 555-555-5555
Additionally, you can extend an existing class to create a new class that has the same functionality of the old class, plus any new functionality you add:
class address_book_entry2 extends address_book_entry {var $email;
function set_email($email) {
$this->email = $email;
}
function display_entry2() {
echo "
Name: " . $this->first . " " . $this->last;
echo "
Number: " . $this->number;
echo "
Email: " . $this->email; }
}
//Usage:
$entry = &new address_book_entry2;
$entry->set_name("Muhammad Faisal","Jawaid");
$entry->set_number("555-555-5555");
$entry->set_email("muhammad_faisal_j@hotmail.com");
$entry->display_entry();
//displays: Name: Muhammad Faisal Jawaid Number: 555-555-5555 Email: muhammad_faisal_j@hotmail.com
phpinfo( )
phpinfo() is a very useful function that allows you to see what version of PHP is running on your Web server, as well as all of the specific settings that are enabled in that version.
Throughout this book, there are sections that ask you to verify your settings. One way to do this is to create a script that includes just the following:
phpinfo();
?>
Upon execution of the script, the browser displays the current PHP settings. This function is especially useful if you are working on somebody else's server and are not quite sure of its capabilities.
No comments:
Post a Comment