JMU
PHP
An Introduction for Programmers


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Characters and White Space
Identifiers
Statements
Comments
Primitive Types
Primitive Types (cont.)
Variables
Assignment Operator
Aliases
Arithmetic Operators
Relational Operators
Relational Operators (cont.)
Logical Operators
The if Statement
while Loops
do-while Loops
for Loops
Functions
Defining Named Functions
Defining Anonymous Functions
Invoking/Executing Functions
Scope
Static Local Variables
Constants
Indexed Arrays
Operating on Indexed Arrays
Associative Array
The Length of an Array
foreach Loops
Arrays of Arrays
Parameter Passing - By Reference

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

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

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

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
Classes (cont.)
Objects
Static Members and Constant Attributes
Static Members and Constant Attributes - An Example
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
Specialization
Specialization (cont)
Abstract Classes
Interfaces
Traits
Dependencies/Modules
Namespaces
File I/O