subscribe: Posts | Comments

Fundamentals of PHP Language

0 comments

php

Basic syntax

Table of Contents

  • Instruction separation
  • Comments

Escaping from HTML

When PHP parses a file, it looks for opening and closing tags,
which tell PHP to start and stop interpreting the code between them. Parsing
in this manner allows php to be embedded in all sorts of different documents,
as everything outside of a pair of opening and closing tags is ignored by the
PHP parser. Most of the time you will see php embedded in HTML documents, as
in this example.

<p>This is going to be ignored.</p>
<?php echo 'While this is going to be parsed.';
?>
<p>This will also be ignored.</p>

You can also use more advanced structures:

Example #1 Advanced escaping

<?php
if ($expression)
{
?>
    <strong>This is true.</strong>
<?php
} else {
?>
    <strong>This is false.</strong>
<?php
}
?>

This works as expected, because when PHP hits the ?> closing tags, it
simply starts outputting whatever it finds (except for an immediately
following newline  ) until it hits another opening tag. The example given
here is contrived, of course, but for outputting large blocks of text,
dropping out of PHP parsing mode is generally more efficient than sending all
of the text through echo() or print().

There are four different pairs of opening and closing tags
which can be used in php. Two of those, <?php ?> and <script language=”php”>
</script>, are always available. The other two are short tags and
ASP style tags, and can be turned on and off
from the php.ini configuration file. As such,
while some people find short tags and ASP
style tags convenient, they are less portable, and generally not recommended.

Note: Also note that if you are embedding PHP within
XML or XHTML you will need to use the <?php ?> tags to remain compliant with
standards.

Example #2 PHP Opening and Closing Tags

1. <?php echo 'if you want to
serve XHTML or XML documents, do like this'
;
?>

2. 
<script language="php">
echo
'some editors (like FrontPage) don't
like processing instructions'
;
</script>

3. 
<? echo 'this is the simplest, an SGML processing
instruction'
; ?>
    <?= expression ?> This is a
shortcut for "
<?
echo
expression ?>"
4.  <% echo ‘You may optionally use ASP-style tags'; %>
<%= $variable; # This is a shortcut for “<% echo . . .” %>


While the tags seen in examples one and two are both always
available, example one is the most commonly used, and recommended, of the two.

Short tags (example three) are only available when they are
enabled via the

short_open_tag
php.ini configuration file
directive, or if php was configured with the
–enable-short-tags
option.

ASP style tags (example four)
are only available when they are enabled via the
asp_tags
php.ini configuration file directive.

Note: Using short tags should be avoided when
developing applications or libraries that are meant for redistribution, or
deployment on PHP servers which are not under your control, because short
tags may not be supported on the target server. For portable,
redistributable code, be sure not to use short tags.

Types

Table of Contents

  • Booleans
  • Integers
  • Floating point numbers
  • Strings
  • Arrays
  • Objects
  • Resources
  • NULL
  • Pseudo-types and variables used in this documentation
  • Type Juggling

Introduction

PHP supports eight primitive types.

Four scalar types:

  • boolean
  • integer
  • float (floating-point number,
    aka double)
  • string

Two compound types:

  • array
  • object

And finally two special types:

  • resource
  • NULL

This manual also introduces some pseudo-types for
readability reasons:

  • mixed
  • number
  • callback

And the pseudo-variable $...
.

Some references to the type “double” may remain in the
manual. Consider double the same as float; the two names exist only for
historic reasons.

The type of a variable is not usually set by the
programmer; rather, it is decided at runtime by PHP depending on the context
in which that variable is used.

Note: To check the type and
value of an expression, use the var_dump() function.
To get a
human-readable representation of a type for debugging, use the gettype()
function. To check for a certain type, do not
use gettype(), but rather the is_type
functions. Some examples:

<?php
$a_bool
=
TRUE
// a boolean
$a_str 
=
"foo";
// a string
$a_str2
=
'foo';
// a string
$an_int
=
12;
// an integer
 

echo
gettype
($a_bool);
// prints out:  boolean
echo
gettype
($a_str);
// prints out:  string
// If this is an integer, increment it by four

if (is_int($an_int))
{
$an_int
+= 4;
}
 

// If $bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool))
{
echo
"String: $a_bool";
}
?>

To forcibly convert a variable to a certain type, either
cast the variable or use the settype() function on it.

Note that a variable may be evaluated with different
values in certain situations, depending on what type it is at the time. For
more information, see the section on Type Juggling.

Variables

Table of Contents

  • Predefined variables
  • Variable scope
  • Variable variables
  • Variables from outside PHP

Basics

Variables in PHP are represented by a dollar sign
followed by the name of the variable. The variable name is case-sensitive.

Variable names follow the same rules as other labels in PHP.
A valid variable name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores. As a regular expression, it
would be expressed thus: ‘[a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*’

Note: For our purposes here,
a letter is a-z, A-Z, and the ASCII characters from 127 through 255
(0x7f-0xff).

Note: $this is a
special variable that can’t be assigned.

<?php
$var
=
'Bob'
;
$Var =
'Joe';
echo
"$var, $Var";
// outputs "Bob, Joe"
 

$4site
= 'not yet';
// invalid; starts with a number
$_4site =
'not yet';
// valid; starts with an underscore
$täyte =
'mansikka';
// valid; 'ä' is (Extended) ASCII
228.
?>

By default, variables are always assigned by value. That is
to say, when you assign an expression to a variable, the entire value of the
original expression is copied into the destination variable. This means, for
instance, that after assigning one variable’s value to another, changing one
of those variables will have no effect on the other. For more information on
this kind of assignment.

PHP also offers another way to assign values to variables:
assign by reference. This means that the new variable simply references (in
other words, “becomes an alias for” or “points to”) the original variable.
Changes to the new variable affect the original, and vice versa.

To assign by reference, simply prepend an ampersand (&) to
the beginning of the variable which is being assigned (the source variable).
For instance, the following code snippet outputs ‘My name is Bob’ twice:

<?php
$foo
=
'Bob'
;             
// Assign the value 'Bob' to $foo
$bar = &$foo;
// Reference $foo via $bar.
$bar =
"My name is $bar";
// Alter $bar...
echo $bar;
echo
$foo;
// $foo is altered too.
?>

One important thing to note is that only named variables may
be assigned by reference.

<?php
$foo
= 25;
$bar = &$foo;
// This is a valid assignment.
$bar = &(24
* 7);
// Invalid; references an unnamed
expression.
 

function
test
()
{
return
25;
}
 

$bar = &test();
// Invalid.
?>

It is not necessary to initialize variables in PHP however
it is a very good practice. Uninitialized variables have a default value of
their type – FALSE, zero, empty string or an empty array.

Example #1 Default values of uninitialized variables

<?php
echo ($unset_bool
? "true"
: "false");
// false
$unset_int
+= 25;
// 0 + 25 => 25
echo $unset_string
. "abc";
// "" . "abc" => "abc"
$unset_array[3]
=
"def";
// array() + array(3 => "def") =>
array(3 => "def")
?>

Relying on the default value of an uninitialized variable is
problematic in the case of including one file into another which uses the
same variable name. It is also a major security risk with register_globals
turned on. E_NOTICE level error is issued in case of working with
uninitialized variables, however not in the case of appending elements to
the uninitialized array. isset() language construct can be used to detect if
a variable has been already initialized.

Constants

Table of Contents

  • Magic constants

A constant is an identifier (name) for a simple value. As the
name suggests, that value cannot change during the execution of the script
(except for magic constants, which aren’t actually constants). A constant is
case-sensitive by default. By convention, constant identifiers are always
uppercase.

The name of a constant follows the same rules as any label in
PHP. A valid constant name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores. As a regular expression, it would be
expressed thusly: [a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*

Example #1 Valid and invalid constant names

<?php 

// Valid constant names
define("FOO",
"something");
define("FOO2",
"something else");
define("FOO_BAR",
"something more");
 

// Invalid constant names
define("2FOO",
"something");
 

// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
define("__FOO__",
"something");
 

?>

Note: For our purposes here, a
letter is a-z, A-Z, and the ASCII characters from 127 through 255 (0x7f-0xff).

Like superglobals, the scope of a constant is global. You can
access constants anywhere in your script without regard to scope. For more
information on scope, read the manual section on variable scope.

Syntax

You can define a constant by using the define()-function.
Once a constant is defined, it can never be changed or undefined.

Only scalar data (boolean, integer, float and string) can
be contained in constants. Do not define resource constants.

You can get the value of a constant by simply specifying
its name. Unlike with variables, you should not
prepend a constant with a $. You can also use the function constant()
to read a constant’s value if you wish to obtain the constant’s name
dynamically. Use get_defined_constants() to get a list of all defined
constants.

Note: Constants and (global)
variables are in a different namespace. This implies that for example
TRUE
and $TRUE are generally
different.

If you use an undefined constant, PHP assumes that you mean
the name of the constant itself, just as if you called it as a string
(CONSTANT vs “CONSTANT”). An error of level E_NOTICE will be issued when this
happens. See also the manual entry on why $foo[bar] is wrong (unless you first
define() bar as a constant). If you simply want to check if a constant
is set, use the defined() function.

These are the differences between constants and variables:

  • Constants do not have a dollar
    sign ($) before them;
  • Constants may only be defined
    using the define() function, not by simple assignment;
  • Constants may be defined and
    accessed anywhere without regard to variable scoping rules;
  • Constants may not be redefined or
    undefined once they have been set; and
  • Constants may only evaluate to
    scalar values.
Example #2 Defining Constants

<?php
define
("CONSTANT",
"Hello world.");
echo
CONSTANT;
// outputs "Hello world."
echo
Constant
; //
outputs "Constant" and issues a notice.
?>

Expressions

Expressions are the most important building stones of PHP.
In PHP, almost anything you write is an expression. The simplest yet most
accurate way to define an expression is “anything that has a value”.

The most basic forms of expressions are constants and
variables. When you type “$a = 5″, you’re assigning ‘5’ into $a. ‘5’,
obviously, has the value 5, or in other words ‘5’ is an expression with the
value of 5 (in this case, ‘5’ is an integer constant).

After this assignment, you’d expect $a’s value to be 5 as
well, so if you wrote $b = $a, you’d expect it to behave just as if you wrote
$b = 5. In other words, $a is an expression with the value of 5 as well. If
everything works right, this is exactly what will happen.

Slightly more complex examples for expressions are functions.
For instance, consider the following function:

<?php
function foo
()
{
return
5;
}
?>

Assuming you’re familiar with the concept of functions (if
you’re not, take a look at the chapter about functions), you’d assume that
typing $c = foo() is essentially just like writing $c = 5, and
you’re right. Functions are expressions with the value of their return value.
Since foo() returns 5, the value of the expression ‘foo()’ is 5. Usually
functions don’t just return a static value but compute something.

Of course, values in PHP don’t have to be integers, and
very often they aren’t. PHP supports four scalar value types: integer values,
floating point values (float), string values and boolean values (scalar values
are values that you can’t ‘break’ into smaller pieces, unlike arrays, for
instance). PHP also supports two composite (non-scalar) types: arrays and
objects. Each of these value types can be assigned into variables or returned
from functions.

PHP takes expressions much further, in the same way many
other languages do. PHP is an expression-oriented language, in the sense that
almost everything is an expression. Consider the example we’ve already dealt
with, ‘$a = 5′. It’s easy to see that there are two values involved here, the
value of the integer constant ‘5’, and the value of $a which is being updated
to 5 as well. But the truth is that there’s one additional value involved
here, and that’s the value of the assignment itself. The assignment itself
evaluates to the assigned value, in this case 5. In practice, it means that
‘$a = 5′, regardless of what it does, is an expression with the value 5. Thus,
writing something like ‘$b = ($a = 5)’ is like writing ‘$a = 5; $b = 5;’ (a
semicolon marks the end of a statement). Since assignments are parsed in a
right to left order, you can also write ‘$b = $a = 5′.

Another good example of expression orientation is pre- and
post-increment and decrement. Users of PHP and many other languages may be
familiar with the notation of variable++ and variable–. These are increment
and decrement operators. In PHP/FI 2, the statement ‘$a++’ has no value (is
not an expression), and thus you can’t assign it or use it in any way. PHP
enhances the increment/decrement capabilities by making these expressions as
well, like in C. In PHP, like in C, there are two types of increment –
pre-increment and post-increment. Both pre-increment and post-increment
essentially increment the variable, and the effect on the variable is
identical. The difference is with the value of the increment expression.
Pre-increment, which is written ‘++$variable’, evaluates to the incremented
value (PHP increments the variable before reading its value, thus the name
‘pre-increment’). Post-increment, which is written ‘$variable++’ evaluates to
the original value of $variable, before it was incremented (PHP increments the
variable after reading its value, thus the name ‘post-increment’).

A very common type of expressions are comparison
expressions. These expressions evaluate to either FALSE or
TRUE
. PHP supports > (bigger than), >= (bigger than or equal to),
== (equal), != (not equal), < (smaller than) and <= (smaller than or equal
to). The language also supports a set of strict equivalence operators: ===
(equal to and same type) and !== (not equal to or not same type). These
expressions are most commonly used inside conditional execution, such as if
statements.

The last example of expressions we’ll deal with here is
combined operator-assignment expressions. You already know that if you want to
increment $a by 1, you can simply write ‘$a++’ or ‘++$a’. But what if you want
to add more than one to it, for instance 3? You could write ‘$a++’ multiple
times, but this is obviously not a very efficient or comfortable way. A much
more common practice is to write ‘$a = $a + 3′. ‘$a + 3′ evaluates to the
value of $a plus 3, and is assigned back into $a, which results in
incrementing $a by 3. In PHP, as in several other languages like C, you can
write this in a shorter way, which with time would become clearer and quicker
to understand as well. Adding 3 to the current value of $a can be written ‘$a
+= 3′. This means exactly “take the value of $a, add 3 to it, and assign it
back into $a”. In addition to being shorter and clearer, this also results in
faster execution. The value of ‘$a += 3′, like the value of a regular
assignment, is the assigned value. Notice that it is NOT 3, but the combined
value of $a plus 3 (this is the value that’s assigned into $a). Any two-place
operator can be used in this operator-assignment mode, for example ‘$a -= 5′
(subtract 5 from the value of $a), ‘$b *= 7′ (multiply the value of $b by 7),
etc.

There is one more expression that may seem odd if you haven’t
seen it in other languages, the ternary conditional operator:

<?php
$first
?
$second
:
$third
?>

If the value of the first subexpression is TRUE
(non-zero), then the second subexpression is evaluated, and that is the result
of the conditional expression. Otherwise, the third subexpression is
evaluated, and that is the value.

The following example should help you understand pre- and
post-increment and expressions in general a bit better:

<?php
function
double
($i)
{
return
$i*2;
}
$b =
$a =
5;       
/* assign the value five into the variable $a
and $b */
$c =
$a++;
/* post-increment, assign original value
of $a
(5) to $c */
$e =
$d = ++$b;
/* pre-increment, assign the
incremented value of
$b (6) to $d and $e */
/* at this point, both $d and $e are equal to 6 */

 

$f =
double($d++);
/* assign twice the value of $d before
the increment, 2*6 = 12 to $f */
$g =
double(++$e);
/* assign twice the value of $e after
the increment, 2*7 = 14 to $g */
$h =
$g +=
10;     
/* first, $g is incremented by 10 and ends with
the
value of 24. the value of the assignment (24)
is
then assigned into $h, and $h ends with the
value
of 24 as well. */
?>

Some expressions can be considered as statements. In this
case, a statement has the form of ‘expr’ ‘;’ that is, an expression followed
by a semicolon. In ‘$b=$a=5;’, $a=5 is a valid expression, but it’s not a
statement by itself. ‘$b=$a=5;’ however is a valid statement.

One last thing worth mentioning is the truth value of
expressions. In many events, mainly in conditional execution and loops, you’re
not interested in the specific value of the expression, but only care about
whether it means TRUE or FALSE. The constants
TRUE and FALSE (case-insensitive) are the two
possible boolean values. When necessary, an expression is automatically
converted to boolean.z

PHP provides a full and powerful implementation of
expressions, and documenting it entirely goes beyond the scope of this manual.
The above examples should give you a good idea about what expressions are and
how you can construct useful expressions. Throughout the rest of this manual
we’ll write expr to indicate any valid PHP
expression.

Operators

Table of Contents

  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Comparison Operators
  • Error Control Operators
  • Execution Operators
  • Incrementing/Decrementing Operators
  • Logical Operators
  • String Operators
  • Array Operators
  • Type Operators

An operator is something that you feed with one or more
values (or expressions, in programming jargon) which yields another value (so
that the construction itself becomes an expression). So you can think of
functions or constructions that return a value (like print) as operators and
those that return nothing (like echo) as any other thing.

There are three types of operators. Firstly there is the unary
operator which operates on only one value, for example ! (the negation operator)
or ++ (the increment operator). The second group are termed binary operators;
this group contains most of the operators that PHP supports, and a list follows
below in the section Operator Precedence.

The third group is the ternary operator: ?:. It should be used
to select between two expressions depending on a third one, rather than to
select two sentences or paths of execution. Surrounding ternary expressions with
parentheses is a very good idea.

Operator Precedence

The precedence of an operator specifies how “tightly” it binds
two expressions together. For example, in the expression 1 + 5 * 3, the
answer is 16 and not 18 because the multiplication (“*”)
operator has a higher precedence than the addition (“+”) operator. Parentheses
may be used to force precedence, if necessary. For instance: (1 + 5) * 3
evaluates to 18. If operator precedence is equal, left to right
associativity is used.

The following table lists the precedence of operators with the
highest-precedence operators listed at the top of the table. Operators on the
same line have equal precedence, in which case their associativity decides
which order to evaluate them in.

Operator Precedence
Associativity Operators Additional Information
non-associative new new
left [ array()
non-associative ++ – increment/decrement
non-associative ~ – (int) (float) (string)
(array) (object) (bool) @
types
non-associative instanceof types
right ! logical
left * / % arithmetic
left + – . arithmetic and string
left << >> bitwise
non-associative < <= > >= <> comparison
non-associative == != === !== comparison
left & bitwise and references
left ^ bitwise
left | bitwise
left && logical
left || logical
left ? : ternary
right = += -= *= /= .= %= &= |= ^=
<<= >>=
assignment
left and logical
left xor logical
left or logical
left , many uses

Left associativity means that the expression is evaluated from
left to right, right associativity means the opposite.

Example #1 Associativity

<?php
$a
= 3
* 3
% 5;
// (3 * 3) % 5 = 4
$a =
true ?
0 :
true ?
1 :
2;
// (true ? 0 : true) ? 1 : 2 = 2
 

$a =
1;
$b =
2;
$a =
$b +=
3;
// $a = ($b += 3) -> $a = 5, $b = 5
?>