More like JavaScript (or Java/C/Shell/Perl/Python) than VBScript (hurrah!) so:
Script is included into a html web page between <? and ?> or <?php and ?> delimiters.
<? is the syntax for opening an SGML processing instruction.
To conform to XML syntax (required for XHTML compliance) always use <?php opening tag.
The short version is not always available, this is enabled either by building PHP with the configure option --enable-short-tags or seting the php.ini directive short_open_tag to 'On'.
There is another shortcut...
<?= expression ?>
... which is equivalent to...
<?php echo expression ?>
... providing the php.ini directive asp_tags is turned on.
Four scalar data types: boolean, integer, double and string
Strictly speaking there is also an unknown data type.
PHP treats data structures, arrays and objects, as types but more on that later.
Type is determined automatically by context - type juggling.
Type casting explicitly changes a data type.
$a = 1; // $a is an integer $b = 1.6; // $b is a double $c = $a + $b; // $c is a double - value 2.6 $d = $c + '7th'; // $d is a double - value 9.6 $d = (int)$d; // $d is an integer - value 9 $e = settype($d, 'double'); // $d is a double again - value 9.0 echo(gettype($e)); // prints boolean
PHP4 has configuration directives which affect the way that environment, get, post, cookie, session and system variables are registered. The php.ini directive register_globals, needs to be set to 'On' for PHP to create separate variables for EGPCS variables. Otherwise the variables are available through the $HTTP_*_VARS global arrays.
$HTTP_ENV_VARS // System variables $HTTP_GET_VARS // Get variables $HTTP_POST_VARS // Post variables $HTTP_COOKIE_VARS // Cookie variables $HTTP_SESSION_VARS // Session variables $HTTP_SYSTEM_VARS // System variables
There are also a number of other predefined variables available to PHP. Have a close look at the output from phpinfo() to make sure that you understand what these variables are and consider how they can be used in web applications. Somewhere around PHP 4.1.0 this system changed to allow a shorter syntax...
$_ENV // System variables $_GET // Get variables $_POST // Post variables $_COOKIE // Cookie variables $_SESSION // Session variables $_SYSTEM // System variables $_REQUEST // Get, post and cookie variables
... although the older $HTTP_*_VARS still appear to function there seems to be some change in the standard environment and system naming.
Variables are automatically created for all data sent from the client. Doesn't matter if it's get, post or cookie data.
e.g. the html form...
<form action="first.php" method="get"> <input type="text" name="userName"/>
... results in a variable in first.php that can be referred to as any of the following ...
$userName - only if globals are registered $HTTP_GET_VARS['userName'] $_GET['userName'] $_REQUEST['userName']
Bear in mind that a particular PHP installation may not have all of the above possibilities available, it depends on the version and the configuration.
The last two are preferred and more likely to be supported.
Delimited with single or double quotation marks.
Variable values are substituted when using double quotes, cf. Perl.
echo is used for output, cf. shell script.
echo "Total cost = $total<br />";
echo is not a function but a PHP language construct so parentheses are not required.
print is similar, being a language construct, but can also be used in a variable function context, echo cannot.
Both echo and print are expensive so avoid using them for outputting static content.
Direct output (the html outside the <?php and ?> delimiters) is faster as it is not parsed by the scripting engine.
the function printf() provides formatted output, e.g.
printf ("Total cost = %.2f <br />", $total);
A dot "." is used to concatenate strings, e.g.
$myString = '$userName = ' . $userName;
The function sprintf() returns a formatted string without generating browser output.
$bottomline = sprintf ("Total cost = %.2f <br />", $total);
Use a backslash to escape reserved characters
echo "<img src=\"C:\\Images\\$imagename\" alt=\"Your picture\" />";
A wide range of string functions are provided in PHP. these are well documented at uk.php.net
See the documentation for chapter and verse on array functions.
Covered remarkably well in the Wrox books
Created with the define() function.
define("VERSION", 3); define("NL", "<br />\n"); echo "Version number = " . VERSION . NL;
Once defined their value cannot be changed. Note there is no $ prefix, perhaps that is why they cannot be interpreted in a quoted string. It is customary to use UPPERCASE for constants.
Functions encourage modular, structured coding and code re-use.
BEWARE! - function names are not case sensitive!
function addAngle($angle, $increase) { $angle += $increase; if ( $angle > 360.0 ) return $angle % 360.0; if ( $angle < 0.0 ) return ($angle % 360.0) + 360.0; return $angle; }
PHP functions have global scope and feature:-
Beware! - variable scope is a popular source of headache for many novice programmers.
Function libraries can be included into a PHP page using require.
Although the use & to indicate reference handling in PHP is NOT the same as the use pointers in C and has some interesting quirks, they can be improve code efficiency by avoiding data replication.
This sort of thing will appeal to old school hackers...
function raise($salary,$percent){ $salary = $salary * (1 + $percent/100); } $wage = 123.0; raise(&$wage,10); echo '$wage = ' . $wage . NL;
PHP appears to figure out when it is dealing with a reference and translate accordingly.
The lack of rigour here leaves something to be desired.
For more on the use of references see the documentation
Starting with PHP 5, the object model was rewritten to allow for better performance and more features. This was a major change from PHP 4. PHP 5 has a full object model.
Among the features in PHP 5 are the inclusions of visibility, abstract and final classes and methods, additional magic methods, interfaces, cloning and typehinting.
PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References
class MyFirstClass { // property declaration public $betty = 'a default value'; // method declaration public function displayMyProperty() { echo $this->betty; } }
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
$instanceA = new MyFirstClass(); // This can also be done with a variable: $className = 'Foo'; $instanceB = new $className(); // Foo() $instanceA->betty = 'value assigned to propert betty'; $instanceA->displayMyProperty()
PHP provides lovely error reporting back to the client so that you have plenty of information for debugging. The level of error reporting is configurable in php.ini from complete silence to complaining about every little thing. As a beginner you should use the error reporting function to reveal all exceptions.
error_reporting(E_ALL);
Beware! prepending fuctions with an @ will suppress error messages. Never do this yourself, not until you are an expert.
If you aren't sure about a chunk of code what do you do?
What useful tricks help to debug code?