Friday, 11 February 2011

Type casting in PHP

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

   1: $foo = 10;                 // $foo is an integer
   2: $bar = (double) $foo;      // $bar is a double



The casts allowed are:
• (int), (integer) - cast to integer
• (real), (double), (float) - cast to double
• (string) - cast to string
• (array) - cast to array
• (object) - cast to object


Note that tabs and spaces are allowed inside the parentheses, so the following are functionally
equivalent:




   1: $foo = (int) $bar;
   2: $foo = ( int ) $bar;

Type juggling in PHP

PHP does not require (or support) explicit type definition in variable declaration; a variable’s type is
determined by the context in which that variable is used. That is to say, if you assign a string value to
variable var, var becomes a string. If you then assign an integer value to var, it becomes an integer.
An example of PHP’s automatic type conversion is the addition operator ’+’. If any of the operands is a double, then all operands are evaluated as doubles, and the result will be a double. Otherwise, the
operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.
$foo = "0";                                    // $foo is string (ASCII 48)
$foo++;                                        // $foo is the string "1" (ASCII 49)
$foo += 1;                                    // $foo is now an integer (2)

$foo = $foo + 1.3;                        // $foo is now a double (3.3)
$foo = 5 + "10 Little Piggies";      // $foo is integer (15)
$foo = 5 + "10 Small Pigs";         // $foo is integer (15)
If the last two examples above seem odd, see String conversion.
If you wish to force a variable to be evaluated as a certain type, see the section on Type casting. If you wish to change the type of a variable, see settype.

Objects in PHP

Object Initialization
To initialize an object, you use the new statement to instantiate the object to a variable.

   1: class foo {
   2: function do_foo () {
   3: echo "Doing foo.";
   4: }
   5: }
   6: $bar = new foo;
   7: $bar -> do_foo ();

PHP Arrays

Arrays actually act like both hash tables (associative arrays) and indexed arrays (vectors).

Single Dimension Arrays
PHP supports both scalar and associative arrays. In fact, there is no difference between the two. You can
create an array using the list or array functions, or you can explicitly set each array element value.

$a[0] = "abc";
$a[1] = "def";
$b["foo"] = 13;

You can also create an array by simply adding values to the array.

$a[] = "hello"; // $a[2] == "hello"
$a[] = "world"; // $a[3] == "world"

Arrays may be sorted using the asort, arsort, ksort, rsort, sort, uasort, usort, and uksort
functions depending on the type of sort you want.


You can count the number of items in an array using the count function.
You can traverse an array using next and prev functions. Another common way to traverse an array is to use the each function.


Multi-Dimensional Arrays
Multi-dimensional arrays are actually pretty simple. For each dimension of the array, you add another
[key] value to the end:
$a[1] = $f; # one dimensional examples
$a["foo"] = $f;
$a[1][0] = $f; # two dimensional

$a["foo"][2] = $f; # (you can mix numeric and associative
indices)
$a[3]["bar"] = $f; # (you can mix numeric and associative
indices)
$a["foo"][4]["bar"][0] = $f; # four dimensional!
You can "fill up" multi-dimensional arrays in many ways, but the trickiest one to understand is how to
use the array command for associative arrays. These two snippets of code fill up the one-dimensional array in the same way:
# Example 1:

   1: $a["color"] = "red";
   2: $a["taste"] = "sweet";
   3: $a["shape"] = "round";
   4: $a["name"] = "apple";
   5: $a[3] = 4;

# Example 2:


   1: $a = array(
   2: "color" => "red",
   3: "taste" => "sweet",
   4: "shape" => "round",
   5: "name" => "apple",
   6: 3 => 4
   7: );

The array function can be nested for multi-dimensional arrays:


   1: <?
   2: $a = array(
   3: "apple" => array(
   4: "color" => "red",
   5: "taste" => "sweet",
   6: "shape" => "round"
   7: ),
   8: "orange" => array(
   9: "color" => "orange",
  10: "taste" => "sweet",
  11: "shape" => "round"
  12: ),
  13: "banana" => array(
  14:  
  15: "color" => "yellow",
  16: "taste" => "paste-y",
  17: "shape" => "banana-shaped"
  18: )
  19: );
  20: echo $a["apple"]["taste"]; # will output "sweet"
  21: ?>

Data types in PHP

PHP supports the following types:


• integer
• floating-point numbers
• string
• array
• object


The type of a variable is usually not set by the programmer; rather, it is decided at runtime by PHP
depending on the context in which that variable is used.
If you would like to force a variable to be converted to a certain type, you may either cast the variable or
use the settype function on it.
Note that a variable may behave in different manners in certain situations, depending on what type it is a
the time. For more information, see the section on Type Juggling.
Integers
Integers can be specified using any of the following syntaxes:


$a = 1234; # decimal number
$a = -123; # a negative number
$a = 0123; # octal number (equivalent to 83 decimal)
$a = 0x12; # hexadecimal number (equivalent to 18 decimal)


Floating point numbers
Floating point numbers ("doubles") can be specified using any of the following syntaxes:

$a = 1.234;
$a = 1.2e3;

Strings
Strings can be specified using one of two sets of delimiters.

If the string is enclosed in double-quotes ("), variables within the string will be expanded (subject to
some parsing limitations). As in C and Perl, the backslash ("\") character can be used in specifying
special characters:
Table 5-1. Escaped characters




sequence meaning
\n newline
\r carriage
\t horizontal tab
\\ backslash
\$ dollar sign
\" double-quote


You can escape any other character, but a warning will be issued at the highest warning level.
The second way to delimit a string uses the single-quote ("’") character, which does not do any variable expansion or backslash processing (except for "\\" and "\’" so you can insert backslashes and single-quotes in a singly-quoted string).
String conversion
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
The string will evaluate as a double if it contains any of the characters ’.’, ’e’, or ’E’. Otherwise, it will
evaluate as an integer.
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an ’e’ or ’E’ followed by one or more digits.
When the first expression is a string, the type of the variable will depend on the second expression.

$foo = 1 + "10.5"; // $foo is double (11.5)
$foo = 1 + "-1.3e3"; // $foo is double (-1299)
$foo = 1 + "bob-1.3e3"; // $foo is integer (1)
$foo = 1 + "bob3"; // $foo is integer (1)
$foo = 1 + "10 Small Pigs"; // $foo is integer (11)
$foo = 1 + "10 Little Piggies"; // $foo is integer (11)
$foo = "10.0 pigs " + 1; // $foo is integer (11)
$foo = "10.0 pigs " + 1.0; // $foo is double (11)

 


For more information on this conversion, see the Unix manual page for strtod(3).

Instruction separation & Comments

Instructions are separated the same as in C or perl - terminate each statement with a semicolon.
The closing tag (?>) also implies the end of the statement, so the following are equivalent:

   1: <?php
   2: echo "This is a test";
   3: ?>
   4: <?php echo "This is a test" ?>


Comments
PHP supports ’C’, ’C++’ and Unix shell-style comments. For example:


   1: <?php
   2: echo "This is a test"; // This is a one-line c++ style comment
   3: /* This is a multi line comment
   4: yet another line of comment */
   5: echo "This is yet another test";
   6: echo "One Final Test"; # This is shell-style style comment
   7: ?>


The "one-line" comment styles actually only comment to the end of the line or the current block of PHP
code, whichever comes first.


   1: <h1>This is an <?# echo "simple";?> example.</h1>
   2: <p>The header above will say ’This is an example’.

You should be careful not to nest ’C’ style comments, which can happen when commenting out large
blocks.


   1: <?php
   2: /*
   3: echo "This is a test"; /* This comment will cause a problem */
   4: */
   5: ?>

Escaping from HTML

There are four ways of escaping from HTML and entering "PHP code mode":
Example 4-1. Ways of escaping from HTML

   1: <? echo ("this is the simplest, an SGML processing instruction\n"); ?>
   2: <?php echo("if you want to serve XML documents, do like this\n"); ?>
   3: <script language="php">
   4: echo ("some editors (like FrontPage) don’t
   5: like processing instructions");
   6: </script>
   7: <% echo ("You may optionally use ASP-style tags"); %>
   8: <%= $variable; # This is a shortcut for "<%echo .." %>



The first way is only available if short tags have been enabled (either by calling short_tags, they are
configured on using the short_tags run-time configuration setting, or they are enabled using the
–enable-short-tags compile-time configuration setting.
The fourth way is only available if ASP-style tags have been enabled using either the asp_tags
configuration setting or the –enable-asp-tags compile-time configuration setting.
Note: Support for ASP-style tags was added in 3.0.4.
The closing "bracket" for the block will include the immediately trailing newline if one is present.