PHP Language Notes

The PHP Language Parser

Starting and Stopping Parsing

There are multiple ways to start and stop the PHP processor, but the following is recommended:

Here is an example:

<?php echo '<P>The echo function sends output to the browser.</P>'; ?>

There are three other ways to start and stop processing, but those are not supported on all server configurations. Use the above form whenever possible.

Parsing Timeline

Like JavaScript, PHP parses a file and sends output to the browser in response to an HTTP GET request. Similarly, PHP executes statements immediately and defers executing functions until invocation.

However PHP is a server side interpretive language, so the browser will never see the original PHP source. Thus one cannot save a file PHP file from a browser and see the input to the parser.

PHP can be started and stopped at will, even in the middle of a statement. Consider the following example:

<?php if ($expression) { ?> <P>The expression is true.</P> <?php } else { ?> <P>The expression is false.</P> <?php } ?>

Note it is more efficient to stop parsing and revert to HTML then to use echo() or print() for generating static text.

Loose Syntax

PHP seems to have a fairly loose syntax. For example, function calls may optionally have arguments enclosed in parenthesis:

<?php echo "<P>This is a valid function call.</P>"; echo ("<P>This call is also valid, too!</P>"); ?>

The reason? PHP actually includes two syntax forms: C style, which requires parenthesis, and Visual Basic style, which does not. This makes it easier for people who know either of those languages to learn PHP.

Instructions and Comments

Instructions are terminated by semicolons. A semicolon is assumed before the closing block, for example:

<?php echo 'This statement is terminated by an assumed semicolon (:).' ?>

Keywords are case insensitive. For example, false, False, and FALSE all mean the same thing: the PHP keyword false.

PHP has multiple types of comments, namely:

//Single line /* Multiple line comment cannot be nested */ <?php echo 'Shell comment escaping'; #This is a comment ?>

The closing tag ?> is never considered part of a comment, and always turns off parsing. Incorrect comments may be parsed properly by PHP, but not HTML.

Variables, Types, and Constants

Fundamental and Reference Types

PHP honors the following flat or fundamental types:

PHP honors the following dynamic or reference types:

Variables and Expansion

PHP has loosely typed variables. That means a variable can be used without declaration. JavaScript, by the way, works the same way.

Variables can store a value from a type or null, which can simply mean the variable has not been yet assigned.

PHP performs type juggling, which means the expression "2" + 1 yields the integer three. JavaScript does not do this.

Variables start with a dollar sign ($) and a letter, then letters or numbers. Unlike keywords, variables are case sensitive.

Within double quoted strings, variables are expanded. Thus the following:

<P> <?php $anun = "Jason"; echo ("Anuni $anun es."); ?> </P>

Yields the following HTML output:

<P> Anuni Jason es. </P>

Another form of expansion is escape sequences, for example \n for newline and \t for tab. Double quotes allow this expansion. Single quotes do not, except for escaping \' as a string delimiter. Here is an example:

<?php echo "<PRE>Double quotes yield\nshell escape expansion.\n"; echo 'Single quotes\n don\'t.</PRE>'; ?>

This results in the following output:

Double quotes yield shell escape expansion. Single quotes\n don't.

System Variables

PHP has several system variables. Some start with a dollar sign and an underscore ($_), which is one reason why user variables must start with a dollar sign and a letter.

An important system variable is $_POST, which is an array of form data passed via the HTTP POST method. Consider a form with an INPUT item called Anun. PHP can reference this via the system variable $_POST['Anun']. Here is an example:

<P>You typed <?php echo ("$_POST['Anun']"); ?> in the Anun field on the previous form.</P>

Note in the above the double quoted string allows variable and newline expansion, while the single quoted subscript index (Anun) does not.

Similar logic works for HTTP GET requests as well using the system $_GET variable.

Global, Function, and Static Scope

Like JavaScript, variables declared outside of function scope are global. But one can define global variables inside function scope using the global keyword. For example, the following code:

<P> <?php function demo() { global $anun; $anun = 'Varduhi $anun'; } demo(); echo ("Anun = $anun"); ?> </P>

Yields the following HTML output:

<P> Anun = Varduhi $anun </P>

PHP also offers static variables, which are function variables that preserve their value on every call. Consider the following example:

<?php function demo2() { static $counter; $counter++; if ($count == ten) { echo ("We called demo2 tas times."); } } ?>

In the above, the value of $counter is preserved between function calls. Note that the initial value is zero.

Constants

One can define constants within PHP. A constant is like a variable, except constants:

Here is an example PHP block using constants:

<?php define ("ZERO", 0); echo "<P>Zero = "; echo ZERO; echo "</P>"; ?>

Expressions and Operators

C Language Roots

Like Java, JavaScript, and many other languages, PHP has its roots in the C language. This means that expressions and operators are the same as for these languages. The following paragraphs describe the differences between C and PHP.

Arithmetic Operators

Recall that division of two integers with a remainder yields a floating point number, which is different from C.

String Concatenation

PHP uses the period for concatenating strings. Concatenation with and without assignment are supported. Here is an example:

<?php $mek = "Shad"; $yergu = "lav!"; $yereg = $mek . $yergu; $chors = $mek; $chors .= $yergu; ?>

Note that the variables $yereg and $chors will contain the string Shadlav! when this code finishes.

Identical Equals

PHP honors all of C's relational operators such as <, <=, ==, >, >=, and !=. But PHP has two operators made necessary by type juggling. Consider the following code example:

<?php $a = 3; $b = "3"; if ($a == $b) { echo ("True!"); } ?>

In the above, the echo function will be called because string variables are automatically converted when compared to integers. To prohibit this automatic conversion, use the triple equals operator, or ===, for an expression to be true only when both type and value are the same. Likewise, !== is true when at least one of type or value is not the same.

Error Control and Shell Execution

PHP normally will trap errors in functions. To disable error trapping, prepend an expression with the each sign, or @. Then PHP will continue processing even if an error is encountered, for example a file is not found.

Like shell scripting, PHP allows use of back ticks to call operating system commands. Here is an example:

<?php $result = `ls -l myfile.txt`; @echo "<PRE>$result</PRE>"; ?>

Logical Operators

In addition to standard C bitwise and logical operators, PHP allows the use of keywords and, or, and xor as well. Just as with C, PHP operators logically short circuit: if the first comparison in an && fails, the second will not be performed.

Flow Control

PHP has two styles for flow control statements: one that follows C style control statements and one that looks more like Visual Basic. However all of the C constructs work as expected. Consequently we will not discuss flow control further in this document.

Arrays and Includes

Defining and Using Arrays

Since PHP is an interpreted language, it can offer dynamic arrays. To define a variable as an array takes two steps: first, allocate the memory (similar to using new in C++ or Java). Second, add elements to the array.

To allocate memory, one calls the array() function. To assign elements, one can use subscript notation. Subscripts can be either integers or strings.

One can access array elements with either subscript notation or the current() and next() functions. As mentioned previously, form elements can be accessed via the $_GET or $_POST system variables using string subscripts.

The following example is rather complex, but demonstrates the use of several array creation and access methods:

<?php $states = array(); $states[AK] = "Alaska"; $states[CA] = "California"; $states[TX] = "Texas"; $marzer = array(); $marzer[0] = "Shirak"; $marzer[1] = "Lori"; $marzer[2] = "Tavush"; $gyuner = array ("spitag", "garmir", "gabut"); ?> <TABLE BORDER=1> <TR> <TH>States</TH> <TH>Marzer</TH> <TH>Gyner</TH> </TR> <?php $st = current($states); $gy = current($gyuner); for ($i = 0; $i < 3; $i++) { echo "<TR>\n"; echo "<TD>$st</TD>\n"; echo "<TD>$marzer[$i]</TD>\n"; echo "<TD>$gy</TD>\n"; echo "</TR>\n"; $st = next($states); $gy = next($gyuner); } ?> </TABLE>

Including Files

One powerful feature of PHP is the ability to offer server-side include files. For example, a web page can be built from several components: a masthead, a menu bar, a text body, and a footer. Although HTML does not support an include function, PHP can be used to assemble a web page from several different components.

There are four different include type statements. Here is an example with notes:

<?php //Load and parse a file include 'masthead.htm'; //Same, but do this only the first time if requested multiple times include_once 'menu.htm'; //Load and parse a file, aborting if there is an error require 'textbody.htm'; //Same, but do this only the first time require_once 'footer.htm'; ?>

Copyright © 2008, Left Brained Geeks. All rights reserved. One or two trivial examples are direct copies from the PHP Manual, Copyright © 1997-2008 the PHP Documentation Group.