- Forward


PHP
An Introduction for Programmers


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Characters and White Space
Back SMYC Forward
  • Character Set:
    • ASCII
    • Variable identifiers are case-sensitive
    • Constant identifiers are case-sensitive
    • Class and function identifiers are case-insensitive
    • Reserved words are case-insensitive
  • White Space:
    • Extra spaces, tabs, carriage returns, and new lines are (mostly) ignored
Identifiers
Back SMYC Forward
  • First Character:
    • Must be a letter, underscore, or a character between 0x7F and 0xFF
  • Subsequent Characters:
    • Can also be a digit
  • A Restriction:
    • An identifier can not be the same as one of the pre-defined reserved words
Statements
Back SMYC Forward
  • Simple Statements:
    • Must end in a ; (except for the last statement)
  • Block/Compound Statements:
    • Consist of one or more simple statements between a { and a }
    • Need not end in a ;
Comments
Back SMYC Forward
  • Line Based:
    • Any text between a # and the end of the line is a comment
    • Any text between a // and the end of the line is a comment
  • Block:
    • Any text between a /* and a */ is a comment
Primitive Types
Back SMYC Forward
  • Integers:
    • Are machine-dependent (and usually correspond to the long type of the C compiler)
    • Hexadecimal integers are formatted as
      0xdigits
    • Binary integers are formatted as
      0bdigits
  • Floating-Point Numbers:
    • Are machine-dependent (and usually correspond to the double type of the C compiler)
Primitive Types (cont.)
Back SMYC Forward
  • Strings:
    • A sequence of Unicode characters
    • Can be concatenated using the . operator
    • String literals can be enclosed in either single quotes or double quotes
    • \ is the escape character and can be used to represent special characters (e.g., \n represents the newline character) and Unicode characters (e.g., \u00e9 is é)
  • Booleans:
    • false, 0, 0.0, "", an array with 0 elements, and NULL all evaluate to false
    • Everything else evaluates to true
Variables
Back SMYC Forward
  • Names:
    • A $ followed by an identifier
  • Types:
    • Variables are untyped
  • Syntax of Declarations:
    • Variables are undeclared (i.e., a variable is created the first time it is assigned a value)
  • Notes:
    • A variable that has not been initialized behaves like NULL
    • Variables can contain names of other variables and the value of the other variable can be referenced using $$ (e.g., $name = "price"; $$name = 5; will assign the value 5 to the variable named price)
Assignment Operator
Back SMYC Forward
  • Assignment:
    • Placing a value into the memory identified by a variable/constant
  • Syntax: Click here for information.
    • variable = literal|expression ;
  • Examples:
    • $height = 14.0; $name = "Bullwinkle";
Aliases
Back SMYC Forward
  • Assignment of a Reference:
    • Place a reference to a variable in another variable
  • Syntax: Click here for information.
    • alias =& variable ;
  • Example:
    • $height = 14.0; $tallest =& $height;
Arithmetic Operators
Back SMYC Forward
  • Basics:
    • Addition (+)
    • Subtraction (-)
    • Multiplication (*)
    • Division (/)
  • Integer Operators:
    • Integer Division (/)
    • Modulo (%)
  • Others:
    • Increment (++) and Decrement (--)
    • Negation (-)
Relational Operators
Back SMYC Forward
  • Comparison:
    • Greater than: >
    • Less than: <
    • Greater than or equal to: >=
    • Less than or equal to: <=
  • Sameness:
    • Equal to: ==
    • Identical to: ===
    • Not equal to: !=
    • Not Identical to: !==
Relational Operators (cont.)
Back SMYC Forward
  • Identical for Numbers:
    • Does not perform implicit type casting
  • Comparison of Strings:
    • Strings consisting of only numeric characters are compared numerically (not lexicographically)
Logical Operators
Back SMYC Forward
  • Basics:
    • Logical AND: &&, and
    • Logical OR: ||, or
    • Logical NOT: !
    • Logical XOR: xor
  • Short Circuiting:
    • Is used
The if Statement
Back SMYC Forward
  • Syntax: Click here for information.
    • if (boolean_expression) statement [else statement]
  • Examples:
    • if ($score < 60) $grade = "F"; if ($bmi >= 30.0) $status = "Obese"; else if ($bmi >= 25.0) $status = "Overweight"; if ($quantity > 100.00) { $discount = 0.10; $note = "Volume Dicount"; }
while Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • while (boolean) statement
  • Examples:
    • $keepGoing = true; while ($keepGoing) { $count += 1; if ($count > 10) $keepGoing = false; } while ($width <= 10) { $area = $height * $width; $width += 1; }
do-while Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • do statement while (boolean);
  • Example:
    • do { $q = $age * $size; $age += 1; } while ($age < 65);
for Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • for (initialization; boolean; update) statement
  • Example:
    • for ($i=0; $i<size; $i++) { $area = $i * $i; }
Functions
Back SMYC Forward
  • Defined:
    • A block of code that is defined once but invoked/executed one or more times
  • Information Exchange:
    • A function may have one or more formal parameters that can be used to provide it with information
    • A function may have a return value that it evaluates to when invoked
Defining Named Functions
Back SMYC Forward
  • Syntax:
    • function [&] identifier([parameters]){ [statement;]...}
  • Example:
    • function area(width, height) { $result = 0; if (($width > 0) && ($height > 0)) $result = $width * $height; return $result; }
Defining Anonymous Functions
Back SMYC Forward
  • Syntax:
    • function([formalparameters]){ [statement;]...}
  • An Example (that assigns an anonymous function to a variable named f):
    • $f = function($width, $height) { $result = 0; if (($width > 0) && ($height > 0)) $result = $width * $height; return $result; };
  • Note:
    • It is not necessary to assign an anonymous function to a variable. For example, it is also possible to pass an anonymous function as an actual parameter of another function.
Invoking/Executing Functions
Back SMYC Forward
  • Syntax:
    • identifier([actualparameters])
  • Example:
    • $size = area(10.2, 20.9);
  • Missing Parameters/Variable Parameter Lists:
    • One can invoke a function with any number of actual parameters (i.e., with fewer actual parameters or more actual parameters than formal parameters)
    • Hence, when writing functions, one should account for this possibility using isset(); default values (i.e., including an assignment) in the formal parameter list; and/or func_num_args() and func_get_arg()
Scope
Back SMYC Forward
  • Global Scope:
    • A variable declared outside of a function can be accessed in any part of the program that is not in a function
    • To access a global variable inside of a function it must be declared global in that function
  • Local Scope:
    • A variable declared in a function can only be accessed in that function
    • Formal parameters can only be accessed in that function
  • Resolving Ambiguities:
    • Local variables take precedence over global variables
  • Super-Global Scope:
    • Some variables provided by PHP have global scope and are accessible inside of functions
Static Local Variables
Back SMYC Forward
  • Explained:
    • A static local variable retains its value between calls to the function in which it is declared
  • Syntax:
    • Include the static modifier in the initialization
Constants
Back SMYC Forward
  • Explained:
    • An identifier for a scalar value that cannot change after it has been set
  • Setting the Value:
    • Use the define() function
  • Example:
    • define("DEPT", "CS"); $course = DEPT . "531";
  • Notes:
    • Constant identifiers are case-sensitive
Indexed Arrays
Back SMYC Forward
  • Defined:
    • An indexed array is an ordered (variable-sized) collection of (not necessarily homogeneous) values
  • Terminology:
    • The numerical position is called the index (and is 0-based)
    • The value is called the element
  • Literals/Initializers:
    • array([value,]...);
  • Examples:
    • $grades = array(90, 85, 73, 88); $bad_idea = array("CS", 139, 4, "B-");
Operating on Indexed Arrays
Back SMYC Forward
  • Accessing Elements with the [] Operator:
    • identfier [ index ]
  • Adding Elements:
    • To add an element to an array one need only assign a value to it. For example:
    • $a = array(2, 4, 6); $a[9] = 20;
Associative Array
Back SMYC Forward
  • Defined:
    • An associative array is a map between a set of keys and a set of corresponding values
  • Literals/Initializers:
    • array([key=>value,]...
  • Examples:
    • $inventions = array("Edison"=>"Light Bulb", "Whitney"=>"Cotton Gin");
The Length of an Array
Back SMYC Forward
  • Some Observations:
    • Arrays can be sparse
    • Using an inappropriate index/key will generate a runtime warning
  • The count() and sizeof() Functions:
    • Return the number of values that are actually set
foreach Loops
Back SMYC Forward
  • Syntax to Access only the Value: Click here for information.
    • foreach (array as element) statement
  • Example:
    • foreach ($purchases as $price) $total += $price;
  • Syntax to Access the Key and Value: Click here for information.
    • foreach (array as key => value) statement
  • Example:
    • foreach ($employees as $name => $salary) echo "$name earns $salary";
Arrays of Arrays
Back SMYC Forward
  • An Observation:
    • Any element of an array can, itself, be an array
  • Accessing Elements:
    • Use the [] operator more than once
Parameter Passing - By Reference
Back SMYC Forward

To pass a parameter by reference, include an & before the variable name in the formal parameter list.

function clear(&$data) { $n = count($data); for ($i=0; $i<$n; $i++) { $data[$i] = 0; } } $sales = array(100, 100, 100); clear($sales); // All the elements of $sales now have the value 0
Parameter Passing - By Value
Back SMYC Forward

To pass a parameter by value, omit the &.

function clear($data) { $n = count($data); for ($i=0; $i<$n; $i++) { $data[$i] = 0; } } $sales = array(100, 100, 100); clear($sales); // All the elements of $sales still have the value 100
Returning - By Reference
Back SMYC Forward

To return by reference, include an & before the variable name in the formal parameter list and use the =& operator to assign the result.

function &get(&$data, $index) { return $data[$index]; } $courses = array("CS139", "CS159", "CS240"); $first =& get($courses, 0); $first = "CS149"; // $courses[0] now contains the string "CS149"
Returning - By Value
Back SMYC Forward

To return by value, omit the & and use the = operator to assign the result.

function get(&$data, $index) { return $data[$index]; } $courses = array("CS139", "CS159", "CS240"); $first = get($courses, 0); $first = "CS149"; // $courses[0] still contains the string "CS139"
Classes
Back SMYC Forward
  • Defined:
    • A collection of attributes/properties and methods/functions
  • Constructors/Destructors:
    • __construct([parameter]..)
    • __destruct()
    • Note: There are two underscore characters!
  • this:
    • A reference to the calling object
  • Membership Operator:
    • ->
Classes (cont.)
Back SMYC Forward
  • Syntax:
    • class identifier { [attribute]... [method]... }
    • where an attribute consists of a visibility (public, protected, or private) and a variable initialization and method consists of a visibility and a function declaration
  • Example:
    • class Course { private $dept = ""; private $number = ""; function __construct($d, $n) { $this->dept = $d; $this->number = $n; } function toString() { return $this->dept . $this->number; } }
Objects
Back SMYC Forward
  • The new Operator:
    • name = new ClassName([parameters])
  • Example:
    • $bestever = new Course("CS", "531"); echo $bestever->toString();
Static Members and Constant Attributes
Back SMYC Forward
  • Static Members:
    • Belong to the class rather than individual instances
    • Declared using the static modifier
    • Accessed externally using the class name and :: operator and internally using self and the :: operator
  • Constant Attributes:
    • Declared using the const modifier (not the define() function)
    • Accessed externally using the class name and :: operator and internally using the identifier
Static Members and Constant Attributes - An Example
Back SMYC Forward
class Course { const FALL = 0; const SPRING = 1; const SUMMER = 2; private $dept = ""; private $number = ""; private $semester = self::FALL; function __construct($d, $n, $s) { $this->dept = $d; $this->number = $n; if (($s === self::SUMMER) || ($s == self::SPRING)) $this->semester = $s; } function getSemester() { return $this->semester; } function toString() { return $this->dept . $this->number; } } $cs531 = new Course("CS", "531", Course::SPRING);
Type Hinting in Methods
Back SMYC Forward
  • Syntax:
    • Include the class name (or the reserved word array) before the formal parameter
  • Implication:
    • A runtime error is generated if the parameter is not of the given type (or NULL)
  • Example:
    • class Student { private $courses = array(); function addCourse(Course $course) { $this->courses[count($this->courses)] = $course; } }
Specialization
Back SMYC Forward
  • Definition:
    • If class A is a subset of class B (i.e., if A has additional attributes and/or methods) then A is said to be a specialization of B
  • Syntax:
    • class derivedclass extends baseclass
Specialization (cont)
Back SMYC Forward
  • Overriding:
    • If the derived class has an attribute/method with the same identifier as an attribute/method in the base class then the method/attribute in the derived calss overrides the method/attribute in the base class
  • Resolving Polymorphism:
    • Normally, the interpreter searches from most specialized to least specialized
  • Changing the Search Order:
    • To call an overriden method in the base class from code in the derived class use parent and the :: operator
    • To ensure that an overriden (or potentially overriden) method in the base class is called by code in the base class use self and the :: operator (rather than $this and the -> operator)
Abstract Classes
Back SMYC Forward
  • Definition:
    • An abstract class is a class that can't have any instances (i.e., one can't, even conceptually, create instances of an abstract class)
  • Abstract Methods:
    • Methods that include only a signature (i.e., no body)
  • Syntax:
    • Include the abstract modifier in the declaration of the class or method
Interfaces
Back SMYC Forward
  • Purpose:
    • Provide a view of a set of services provided by a class
  • Interpretations:
    • An interface is a "contract"
    • A class that realizes an interface promises that it will implement all of the methods in the interface
  • Syntax:
    • An interface is declared/defined just like a class but with class replaced by interface
    • A class that realizes an interface indicates that it does so using implements
Traits
Back SMYC Forward
  • Purpose:
    • Provide a mechanism for sharing code outside of a class hierarchy
  • Syntax:
    • A trait is declared/defined just like a class but with class replaced by trait
    • A class that makes use of one or more traits indicates that it does so using a use [traitname,]...; statement
Dependencies/Modules
Back SMYC Forward
  • The include and require Statements:
    • Load and evaluate a specified file
    • include generates a warning and require generates a fatal error if the file is not found
  • The include_once and require_once Statements:
    • Will not load/evaluate the file more than once
Namespaces
Back SMYC Forward
  • Purpose:
    • Avoid name collisions
  • Declaring:
    • Use the namespace statement
    • Use backslashes to create a hierarchy
  • Using Namespaces:
    • Use the fully-qualified name to disambiguate if necessary
    • Creating Aliases for Fully-Qualified Names: Use the use statement
File I/O
Back SMYC Forward
  • Existence:
    • file_exists()
  • Opening/Closing:
    • fopen() and fclose()
  • Reading/Writing:
    • fread() and fwrite()
    • fscanf() and fprintf()
There's Always More to Learn
Back -