CPSC225/Notes/PHP Basics

Contents

PHP Basics: Notes From Chapters 2-3 of Williams and Lane

Note: The text is Hugh Williams & David Lane, Web Database Applications with PHP and MySQL, which has an online website that contains the book's source code.

Preliminaries: Displaying Error Messages

This assumes you have already installed PHP on your computer. By default, most PHP installations will not display error messages in the browser. This is a security feature. However, during development it's a good idea to display error messages. To set up your environment to display errors:

1. Find the PHP configuration file php.ini on your system. (On the Mac it is: /usr/local/php5/lib/php.ini)

On Macintosh or Linux: $locate php.ini

2. Edit php.ini and search for the these lines (which will not be consecutive):

error_reporting = E_ALL
display_errors = Off

and change them to:

error_reporting = E_ALL & ~E_NOTICE | E_STRICT
display_errors = On

3. Restart Apache:

$ sudo apachectl restart

Language Basics

  • The Hello World example. Download this example and test it. Edit it so that "print" is misspelled. Reload the page. It should print an error message:
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /Users/rmorelli/Sites/testphp/helloworld.php on line 10
  • Output statements: echo vs. print -- echo can print a list
  • String literals: 'hello $name' vs. "hello $name" vs. "My computer has {$memory}MBytes of RAM"
  • Variables are weakly typed and need not be declared before used.
  • Types: scalars: boolean, float, integer, string and compound: array, object and special: null.
  • A variables type can change over its lifetime.
  • Constants: define("PI", 3.14159); Immutable and accesible globally.
  • Expressions and Operators: Concatenate uses dot (.).
  • If/else, switch, and loop statements: More or less the same as Java or C (except foreach-- see below). Short circuit evaluation is used on all conditional expressions.

Functions

  • Prototypes: returnType name(paramType paramName...)
  • Parameters are weakly typed: Be careful!
  • Type conversion can be done using casting operators, (integer), or functions:
string strval(mixed var)
integer intval(mixed var [, integer base])
float floatval(mixed var)
boolean settype(mixed var, string type)
  • Automatic type conversions. Note that "100" + 15 gives 115 (unlike Java). See table 2-1, page 39.
  • Examining Variable Type: There are lots of functions for this, including:
boolean is_int(mixed var)
boolean is_string(mixed var)
  • Is equal operator (==) vs. is identical operator (===). Is identical includes same type and value.

Functions for Debugging

string gettype(mixed expression) -- returns the expression's type.
print_r(mixed expression) -- displays arrays.
var_dump(mixed expression [,mixed expression...]) -- prints type and value.  
boolean isset(mixed var) -- returns true iff var has been assigned a non-null value
boolean empty(mixed var) -- returns true iff var equals false
unset(mixed var [,mixed var [,...]]) -- destroys one or more variables.

User Defined Functions

  • The Bold Face example.
  • Note that parameter types and return type are note declared. The same function can give different types of results. Be careful!
  • Variable scope: PHP does complain about undeclared variables. Variables used for the first time in functions have local scope.
  • Global variables are declared within functions using the keyword global. (Opposite of some other languages.)
  • Static variables are declared within functions with the keyword static. The retain their their state between function calls.
  • Pass-by-Value: By default, values are passed to a function's parameters.
  • Default Parameter Values: Assignment expressions can be used to give default values to parameters.

Include and Require Files

  • PHP can include source code from other files including function definitions with the include and require commands. It is always best to use include_once and require_once.

Arrays

  • PHP arrays are sophisticated and powerful and come with lots of built-in functionality.
  • $numbers = array(5, 4, 3, 2, 1); -- automatically indexed 0..4
  • $words = array("Web", "Database", "Applications"); -- indexed 0..2
  • PHP will automatically assign indexes:
$shopping = array();
$shopping[] = "Milk";   -- indexed at 0
$shopping[] = "Coffee"; -- indexed at 1
$shopping[] = "Sugar"; -- indexed at 2
  • print_r($shopping); -- prints the array in a nice format.

Associative Arrays

  • PHP Arrays can have strings as keys (or indices).
  • $array = array("first"=>1, "second"=>2, "third"=>3); -- array["second"] contains 2
  • Removing an array element: unset($array["first"]) -- No longer anything at that location.
  • New elements (regardless of index) are always appended to the end of the array.
$numbers = array(1=>"one", 3->"three", 5->"five");
$numbers[2] = "two";  -- added after 5.

Foreach Loop with Arrays

foreach(array_expression as $value) {...} 
foreach(array_expression as $key=>$value) {...} 
  • Examples:
$lengths = array(0, 107, 202, 400, 475);
foreach($lengths as $cm)
{
  $inch = $cm / 2.54;
  print "{$cm} centimeters = {$inch} inches\n";
}
$sounds = array("cow"=>"moo", "dog"=>"woof", "pig"=>"oink", "duck"=>"quack");
foreach($sounds as $animal => $sound)
{
  print "A {$animal} goes {$sound}\n";
}

Built-in Array and String Functions

PHP has a lot of built-in array functions and lots of built-in string functions.

References

Hugh Williams & David Lane, Web Database Applications with PHP and MySQL