In this section we will cover:
- PHP Tags
- File inclusion
- Data types & typecasting
- Variables and constants
- Operators
- Conditionals
- Iteration
- Functions
- Objects
- Tags
- Tags “drop” you out of HTML and into PHP mode
- PHP recognizes several types of tags:
- Short tags: <? ?>
- Special tags: <?= ?>
- Regular tags: <?php ?>
- ASP tags: <% %>
- HTML script tags.
- File Inclusion
- External files can be included in a script using either include() or require()
- Both are constructs , not functions :
include (‘myfile.php’); or include ‘myfile.php’;
- They behave in exactly the same way, except for how they handle failure include generates a warning require throws an error.Upon inclusion, the parser “drops off” of PHP mode and enters HTML mode again.
- Variants: include_once()/require_once()
Prevent multiple inclusions from within the same script. - Data Types
- PHP is not a typeless language
- It supports many different data types
- It is loosely typed
- The interpreter automatically “juggles” data types as most appropriate
- “Most appropriate” doesn’t necessarily mean always appropriate
- Data Types — Numeric/Boolean
- PHP recognizes two types of numeric values:
Integers Floats - Boolean values are used for logic operations
True / False
Easily converted to integers: non-zero / zero - Result type of operations depends on types of operands
For example: int + int == int — int / float == float
int / int == int or float - Numbers can be specified in a number of ways:
Decimal (123), Hexadecimal (0x123) and Octal (0123) - Data Types — Strings
- Strings are heterogeneous collections of single-byte characters
They don’t necessary have to be text
They can represent Unicode as well, but cannot be manipulated by the standard PHP functions - PHP supports three ways of declaring strings:
Single quotes: ‘test 1 2 3’
Double quotes: “test 1 2 3\n”
Heredoc syntax: <<EOT; - Main differences:
Support for variable substitution / escape sequences
All strings support newline characters - Data Types — Arrays
- Arrays are ordered structures that map a key to
a value - Values can be of any type—including other
arrays - Keys can be either integer numeric or strings
Keys are unique
Negative numbers are valid keys - Data Types — Resources / Null
- Resources are special containers that identify
external resources
They can only be operated on directly as part of
logical operations
They are usually passed to C-level functions to act on
external entities
Examples: database connections, files, streams, etc. - NULL is a special value that indicates... no value!
NULL converts to Boolean false and Integer zero - Data Types — Objects
- Objects are containers of data and functions
The individual data elements are normally called
properties. The functions are called methods
Individual members (methods / properties) of an
object are accessed using the -> operator
We’ll cover objects in more depth later in this section - Typecasting
- PHP’s ability to juggle among different data
types is not entirely dependable - There are circumstances in which you will want
to control how and when individual variables
are converted from one type to another - This is called Typecasting
- Typecasting — Integers
- You can typecast any variable to an integer
using the (int) operator:
echo (int) “test 1 2 3”;
- Floats are automatically truncated so that only
their integer portion is maintained
(int) 99.99 == 99- Booleans are cast to either one or zero:
(int) TRUE == 1 — (int) FALSE == 0- Strings are converted to their integer equivalent:
(int) “test 1 2 3” == 0 , (int) “123” == 123
(int) “123test” == 123 // String begins with integer- Null always evaluates to 0
- Typecasting — Booleans
- Data is cast to Boolean using the (bool)
operator:
echo (bool) “1”; - Numeric values are always TRUE unless they
evaluate to zero - Strings are always TRUE unless they are empty
(bool) “FALSE” == true - Null always evaluates to FALSE
- Typecasting — Strings
- Data is typecast to a string using the (string)
operator:
echo (string) 123; - Numeric values are converted to their decimal
string equivalent:
(string) 123.1 == “123.1”; - Booleans evaluate to either “1” (TRUE) or an
empty string (FALSE) - NULL evaluates to an empty string
- Numeric strings are not the same as their integer
or float counterparts! - Typecasting — Arrays / Objects
- Casting a non-array datum to an array causes a
new array to be created with a single element
whose key is zero:
var_dump ((array) 10) == array (10); - Casting an object to an array whose elements
correspond to the properties of the object
Methods are discarded - Casting a scalar value to an object creates a
new instance of stdClass with a single property
called “scalar”. Casting an array to an object create an instance of stdClass with properties equivalent to the array’s elements - Identifiers / Variables / Constants
- Identifiers are used to identify entities within a script. Identifiers must start with a letter or underscore and can contain only letters, underscores and numbers.
- Variables
Containers of data.
Only one data type at any given time.
Variable names are case-sensitive identifiers prefixed
with a dollar sign ($my_var)
Variables can contain references to other variables - Constants
Assigned value with declare(), cannot be modified
User-defined constants are not case-sensitive - Substitution / Variable variables
- Variables can be substituted directly within a double-quoted or Heredoc string
$a = 10;
echo “\$a is: $a”; // Will output $a is: 10 - Variables values can be used to access other
variables (variable variables):
$a = “b”;
$b = 10;
echo $$a; // will output 10 - Statements
- Statements represent individual commands that the PHP interpreter executes
Assignment: $a = 10;
Construct: echo $a;
Function call: exec ($a); - Statements must be terminated by a semicolon
Exception: the last statement before the end of a PHP
block - Operations
- PHP supports several types of operations:
Assignment
Arithmetic
Bitwise
String
Comparison
Error control
Logical - Operations — Assignment
- The assignment operator ‘=’ makes it possible to assign a value to a variable
$a = 10;- The left-hand operand must be a variable
Take advantage of this to prevent mistakes by
“reversing” logical operations (as we’ll see later)
10 = $a; // Will output error - The left-hand operand must be a variable
- Operations — Arithmetic
- These operators act on numbers and include the
four basic operations:
Addition: $a + $b
Subtraction: $a - $b
Multiplication: $a * $b
Division: $a / $b - Remember that dividing by zero is illegal
- They also include the modulus operator
Determines the remainder of the integer division
between two numbers: 10 % 4 = 2
Unlike proper modulus, PHP allows a negative right-hand operand - 10 % -4 = 2
- Operations — Bitwise
- Bitwise operations manipulate numeric values at the bit level
AND (&) — set bit if it is set in both operands - 1 & 0 == 0
OR (|) — set bit if is is set in either operand - 1 | 0 == 1
XOR (^) — set bit if it is set in either, but not both - 1 ^ 1 == 0
NOT — invert bits - ~0 == -1
Shift left/right (<>) - shift bits left or right - 1 << 2 ==4 == 8 << 1
- Excellent shortcuts for integer multiplications by powers of two
- Operators — Combined
- Numeric and bitwise operators can be combined with an assignment:
$a += 10 is equivalent to $a = $a + 10; - This does not apply to the NOT operator, since it’s unary
- Operators — Error Control
- PHP support several different levels of errors
- Error reporting can be tweaked either through
PHP.INI settings or by calling error_reporting(). - Remember that the exam assumes the default
“recommended” INI file
Warning and Notices are not reported! - Error reporting can be controlled on a statement-by-statement basis using the @
operator:
@fopen ($fileName, “r”);
This only works if the underlying functionality uses PHP’s
facilities to report its errors - Operators — Inc/Dec and String
- Incrementing and decrementing operators are special unary operators that increment or decrement a numeric variable:
Postfix: $a++
Prefix: ++$a
You cannot perform two unary operations on the same variable at the same time— ++$a-- will throw an error - The only string operation is the concatentaion
(.), which “glues” together two strings into a third
one
“a” . ‘b’ == ‘ab’ - Operators — Comparison / Logical
- Comparison operators are used to compare values:
Equivalence: == != - Equivalence operators do not require either of their operands to be a variable
Identity: === !==
Relation: <, <=, >=, > - Logical operators are used to manipulate Boolean values:
AND (&&) — TRUE if both operands are TRUE
OR (||) — TRUE if either operand is TRUE
XOR (xor) — TRUE if either operand is TRUE, but not both
NOT (!) — Reverses expression - Operator Precedence
- The precedence of most operators follows rules
we are used to—but not all of them
Example: “test ” . 1 + 10 . “ 123” == “1 123” - There are two variants of logical operators
The “letter” operators AND, OR differ from their “symbol” equivalents &&, || in the fact that they have lower precedence - Conditionals — if-then-else
- Conditionals are used to direct the execution
flow of a script
if (condition) {... statements ...
} else {
... statements ...
}
- Alternative short form:
$a = (cond) ? yesvalue : novalue; - Conditionals — case/switch
- Case/switch statements allow you to verify a
single expression against multiple expressions:
switch (expr) {
case expr1 :
... statements ...
break;case expr2:
... statements ...
break;default:
... statements ...
break;
} - Iterators — While
- While loops are the simplest form of iterator; they
allow you to repeat a set of statements while a
condition evaluates to TRUE:
while (expr) {... statements ...
}
- Iterators — Do...while
- Do...while loops are equivalent to while loops,
but the condition is evaluated at the end of the
loop, instead of the beginning:
do {... statements ...
} while (expr);
This means that the statement block is executed at
least once - Iterators — For and Foreach
- While and do...while are the only indispensible iterators in any language.
- For convenience, PHP includes for loops:
for (initial; condition; incremental) {
... statements ...
} - Foreach loops can be used to iterate through an aggregate value:
foreach ($array as $k => $v) {
... statements ...
}
Important: $k and $v are assigned by value!
Works on objects, too! - Iterators: continuing/breaking
- Loops can be continued using the continue construct:
while ($a == 1) { if ($b == 2) continue; } - Loops can be interrupted using the break construct:
while ($a == 1) { if ($b == 2) break; } - Multiple nested loops can be continued/broken at once:
continue 2;
Remember the semicolon at the end of the break or
continue statement! - Functions
- Functions allow for code isolation and reuse
function myfunc (&$arg1, $arg2 = 10)
{
global $variable;... statements ...
} - echo myfunc (10);
• Pay attention to variable scope!
• Functions can support variable parameters:
func_num_args();
fung_get_arg(); - OOP: Classes and Objects
- Classes define the structure of objects:
class myClass {
var $myVar;function myClass() { // constructor
$this->myVar = 10;
} - Objects represent individual instances of a class:
$a = new myClass;
$a->myVar = 11; - Objects support dynamic methods and properties:
$obj->$var(); - OOP: Classes as Namespaces
- PHP does not support namespaces (this is true also of PHP 5), but classes can simulate their behaviour:
class class encode {
function base64($str)
{
return base64_encode($str);
}
}echo encode::base64("my string");
- OOP: Objects and References
- In PHP 4, objects receive no special treatment:
they are essentially arrays with embedded functions
This means that references to objects must be handled
with care. - Passing/assigning an object is normally done by
value, not by reference, even when using new - OOP: Objects and References
- The $this special variable cannot be passed by reference, even if you use the & operator. However, you can embed $this in a global array and circumvent this problem (albeit in a horrible way):
• class obj {
var $prop;
function obj($arg)
{
global $obji; // import variable into local scope
$obji[] = $this; // get a copy of current class
$this->prop = $arg;
}
}
$obj = new obj(123);
var_dump($obj->prop != $obji[0]->prop); // FALSE - OOP: Inheritance
- Inheritance makes it possible to create classes (“subclasses”) that are based on other classes (“superclasses”):
class base {
function base()
{
}
}class main extends base {
function main()
{
parent::base();
}
} - OOP: Object Serialization
- Serialization is the process of reducing an aggregate (array or object) to a scalar (string)
- Serialization is a mostly automatic process, but for objects it is possible to exercise a certain amount of control:
__sleep()
__wakeup()
Useful for dynamically-generated properties, such as
database connections and file descriptors
Classes must be declared before their instances are
unserialized
>
»
- 1942 reads












