Php Basics

This document is meant to be read in conjunction with the on-line PhpBasics website. The website is also available on the Computer Science web server:
PhpBasics on the CS Server
We describe a local installation of the PhpBasics project in NetBeans. See either Windows, Linux, or MAC). The demo scripts can be executed both through the web or command-line. In order to execute through the command-line, simply navigate a shell to the folder
/PATH/TO/PhpBasics/examples
and, for each SCRIPT.php, run:   php SCRIPT.php

NetBeans Php plugin

For NetBeans Php support, you will need to have the Php plugin installed in NetBeans:
  1. Select Tools ⇾ Plugins from the menus
  2. Click the Available Plugins tab, scroll down and check Php. Then click the Install button.

Local NetBeans project installation

Download the source archive PhpBasics.zip. Install the archived directory PhpBasics into the directory representing your "/default" website (refer to the above section and the Apache/Php/MySQL setup for Windows, Linux, or MAC). Start up NetBeans and follow these steps to create the PhpBasics project in your default directory.
  1. Extract the PhpBasics project into your default directory.
  2. Select File ⇾ New Project
  3. From the PHP category, choose PHP Application with Existing Sources, then Next.
  4. Use the Browse button to select the correct Sources Folder as the location of PhpBasics folder just extracted. The Project Name should be correctly set to PhpBasics. Check settings and click Next.
    Project Name: PhpBasics
    Sources Folder: path-to-default-directory/PhpBasics
    PHP Version:   (at least)
  5. In the Run Configuration window, choose these then click Finish.
    Run As: Local Web Site
    Project URL: http://localhost/default/PhpBasics/
  6. Select Run ⇾ Run Main Project or, with the project selected, use the green arrowrun icon.
The installed website should correspond to the URL
http://localhost/default/PhpBasics
This demo application allows the user to choose a Php script to execute and see the results in the display windows. The relevant files for the demo are:
examples/                  the script files
include/examples-list.txt  the order in script files are listed

Server-side web programming

Web applications are client/server applications where the web browser, as client, initiates the connection. The server is actually a service program identified by a number called the port which distinguishes it from other service programs. The browser client initiates the interaction with a URL request:
protocol://data_source
where the protocol includes http, file, https, ftp, etc. The protocol dictates a default port (e.g., http=80, https=443), or a port can be specified:
protocol://server/data_source
protocol://server:port/data_source
The data_source can be a file (static HTML), a program or a directory (in which case some default file or programis used). Server-side programming means that the HTTP request causes a program initiated by the web server to generate the HTML response sent back to the browser. Server-side programming stands in contrast to client-side programming which is programming (commonly JavaScript) is done by the client after the response has been receieved.

Php execution and syntax

The Php language, initiated in 1994, was written for Web applications. Php can be executed in three ways:
  1. as an Apache module (this is what we're interested in)
  2. as a command-line program
  3. as an executable running as a CGI program
We will make use of the first two of these. Ubuntu Linux systems presents all three with features, such as init files, separately; other operating systems will combine features. The CGI-style execution is common in systems which do not use Apache, such as Lighttpd, Nginx.

Php is syntax, like that of many other languages, is based on C. Php inherits a number of syntactic features from Perl. Php code is commonly embedded directly into HTML syntax, meaning that any HTML program, with the extension ".html" replaced by ".php", becomes a Php program. The most Php code is used within dedicated tags which look like this:
<?php
 ...
?>
Php scripts can also contain only Php code, in which case it is usually better to omit the closing tag. For example, if a Php script generates a binary image any extra white-space can cause an error.

The echo command is used to send output to the response, and so to the browser. Php also has a print function but it permits only a single argument. Here is a "hello world" script:

hello.php
<pre>
<?php
echo   "1: hello world\n";
print( "2: hello world\n" );
echo   "3:", "hello ", "world", "\n";
echo   "4:", "hello " . "world" . "\n"; 
print( "5:" . "hello " . "world" . "\n" );  // OK
//print("5a:", "hello ", "world", "\n");  /* fails */
 
# newlines can be embedded in quotes
echo "6: hello
there
world\n";
 
# this is interpolated "heredoc" style
echo <<<ENDSTR
7: hello (and not the END of the)
"world"
ENDSTR;
/*
  ENDSTR must start at first position 
*/
?>
</pre>
A couple of notes:
  1. As you see, Php supports all common commenting styles (Java/Python/Perl):
    # comment line
    // comment line
    /* 
      comment region
    */
    
  2. The dot operator (.) is string concatenation. This novel usage is found in Perl and Php only.

Scalar types and variables

The main scalar types are string, integer, double, boolean and NULL. All Php variables use the $ prefix. Php recognize that variables can be in an undefined state which is, in many respects, the same as having the NULL value. A built-in function gettype reveals the type of the value of a variable. Strings are created by by: Here are some points about strings:

Undefined variables and NULL

In programming terms, using an undefined variable is often the result of a programming mistake, e.g.:
$my_var = 10;
echo "the value is $myvar";   // (A)
In Php, using an undefined variable is not an error, but a warning is given for inadvertent usage as in the above script. What you will see (depending on the Php configuration) is this message:
Notice: Undefined variable: myvar in ...
The response to using an undefined variable is called a Notice. The correct way to regard a possibly undefined variable is to test it with the isset function, e.g.:
if ( isset($myvar) ) {
  echo "the value is $myvar";
} 
else {
  echo '$myvar is undefined';  // (B)
}
An undefined variable behaves like NULL. They both print the empty string. If I were to make the assignment
$myvar = NULL;
then, in the second program undefined and NULL would both trigger the execution of line (B). However, the line (A) in the first program segment would not give a notice. There is a similar testing function is_null (with the opposite sense of isset), but using is_null($myvar) on an undefined variable gives a notice.

Finally, if you do actually want to return a variable to its unset state, you can use the function:
unset($myvar);
however, setting to NULL would have (mostly) the same outcome.

Notices can be generated for a variety of programmatic "issues." The way that Php deals with notices is dictated by two important initialization settings:
display_errors  =  either "Off" or "On"
error_reporting =  an integer whose bits specify which errors to report
In development mode errors are usually displayed on the page (never in a production mode!). The default values of these two settings differ by operating systems and Php versions. In development mode, however, it is important to see everything going on using this setting:
error_reporting = E_ALL
which is what I have indicated that you use in a Php/Apache installation. It is possible to control the error level at the program level like this:
error_reporting(E_ALL & ~E_NOTICE);
However DO NOT USE THIS. You should always favor handling undefined variables correctly.

Sample script for scalar usage

scalars.php
The script includes the useful var_dump function which displays both the value and the type of a variable.

Php controls

Php control syntax is close to C. Here are some key points:

Sample scripts for control features

controls1.php
controls2.php

Arrays

The Php array represents both an unbounded list, like the Java List implementations, and a map, or associative array, like the Java Map implementations. Array literals are created using the "array" operator, or, since version 5.4, the [ .. ] syntax. For example, a list and a map:
$colors = array( "red", "green", "blue", ) // trailing comma OK
$ages = array(
  "joe" => 33,
  "bill" => 22,
  "susan" => 45,
);
This syntax also works for Php 5.4 and above:
$colors = [ "red", "green", "blue", ];  // trailing comma OK
$ages = [
  "joe" => 33,
  "bill" => 22,
  "susan" => 45,
];
Lists, as expected, have a positional key:
$colors[1]  is  "green"
Maps use the same syntax, except that the key is explicit:
$ages["joe"]  is  33
A unique feature of Php is the way lists are sequentially generated. For example this code also generates $colors:
$colors[] = "red";
$colors[] = "green";
$colors[] = "blue";
In particular, you almost never should create elements in a list by assigning values to positions. It is, of course, OK after the position is created to reassign its value, e.g.,
$colors[1] = "orange"; // OK after $colors[1] has been defined
Like a list, a map can be generated sequentially as well.
$ages["joe"] = 33;
$ages["bill"] = 22;
$ages["susan"] = 45;
Another key feature of Php is that the entry order is preserved when (key/value) pairs are extracted from a map, meaning that the Java equivalent would be the LinkedHashMap.

Here are some other points:

Sample scripts for arrays

arrays1.php
arrays2.php

Array maps as Sets

Php, unlike Java, has no representation of Sets per se. However, one can easily use an array map to implement a set (this is what Java does under the hood). The idea is to simply make the set elements keys of the map and assign a "true" value to each key to signify presence in the set.

Consider this example of a set of food items consisting of {"apples", "lettuce", "broccoli"}:
$food_items = [];              // empty set
 
$food_items['apples'] = 1;     // add apples
$food_items['lettuce'] = 1;    // add lettuce
$food_items['broccoli'] = 1;   // add broccoli
unset($food_items['apples']);  // remove apples

Functions

Php functions are declared using the function keyword in a syntax similar to Java, except that there are no data types. Here are other aspects of functions: Reference parameters or reference variables can be regarded as "synonyms". This illustrates reference variables:
$a = 11;
$b =& $a;   // $b is a synonym of $a
 
echo '$a = ', $a, "\n";  // 11
echo '$b = ', $b, "\n";  // 11
 
$b = 22;
echo '$a = ', $a, "\n";  // 22
More useful are reference parameters where the parameter is a synonym for the actual variable passed into it. This allows a function to "send back" information from a call through the parameters.

Sample scripts for functions

funcs1.php

File inclusions

Functions and classes are usually made available to Php scripts via file inclusions much like the inclusions in C/C++ and quite different from Java imports. Php uses one of the operators include, require, include_once or require_once to create an inclusion.

The difference between include and require is how they handle failure when the target file doesn't exist: include produces a warning while require results in a fatal error. If we expect that a file may or may not exist and we want to use include, then it is typical to use a statement like this:
@ include "some_file";
where the initial @ causes Php to suppress the warning that this statement may generate. In this case, if the file does not exist, nothing will happen.

The "_once" alternatives avoid the problem of multiple inclusion when multiple included files have included the same base file. Dealing with multiple inclusion in C/C++ involves the subtle notions "#ifndef ___/#define/#endif" constructs. Php makes it very easy to avoid multiple inclusions with this _once construct.

The moral is that, for the most part, probably you want to do file inclusion via:
require_once "some_file";
If you want to include files from some global directory you might want to add this directory to the configuration variable include_path, which is usually done programmatically like this:
$path = '/PATH/TO/INCLUSIONS';
set_include_path( get_include_path() . PATH_SEPARATOR . $path );

Classes and Objects

Php classes imitate many of the features of Java. There is a specific class construct, a new operator, data members, a constructor and class hierarchy (the extends operation). Here are other points: A class can be created from a specific type declaration.
class Person {
  var $first;
  var $last;
}
A variable of this type are declared using the new operation:
$p = new Person();
The var declarator can also be replaced by public. We can then access the members directly:
$p->first = "John";
$p->last = "Smith";
A feature of Php objects, similar to JavaScript objects is the ability to create members dynamically. For example we can add a new member, age, to a specific Person object:
$p->age = 50;
If we make the members private, then we can only access these member through member functions.
class Person {
  private $first;
  private $last;
}

Generic objects

We do not need to declare public members at all, just start using them. Php has a "generic object" class, stdClass, which can be used to create any object without explicit class declaration:
$q = new stdClass();
$q->first = "Bob";
$q->last  = "Martin";

An array map is an aggregate which holds a variable for each key. Likewise, a stdClass object holds a variable for each member. These two constructs express very similar ideas and Php allows you to go from one to the other using the (array) and (object) casting operations. A sample is indicated below. This object/map equivalence is even more transparent in JavaScript where there is no need for casting to go from one form to the other.
$arr = array( "key1" => 'value1', "key2" => "value2" );
$obj = (object) $arr;
 
$obj->key1 = "value1";
$obj->key2 = "value2";
$arr = (array) $obj;

Sample scripts for classes and objects

classes1.php
classes2.php


© Robert M. Kline