05 February 2008

PHP Programing | PHP Basic | chapter 2 Language Reference

After installing and configuring the PHP and webserver we start knowing about PHP language reference.PHP is a scripting language that can embeded in the HTML page same as javascript or vbscript. To insert PHP script there few ways to do for example :
1.
2.

3.


4. <% echo ("You may optionally use ASP-style tags"); %>
<%= $variable; # This is a shortcut for "<%echo .."

The first way is only available if short tags have been enabled. This can be done by enabling the short_open_tag configuration setting in the PHP config file, or by compiling PHP with the --enable-short-tags option to configure.
The second way is the generally preferred method, as it allows for the next generation of XHTML to be easily implemented with PHP.
The fourth way is only available if ASP-style tags have been enabled using the asp_tags configuration setting.
PHP supports the following types:
· array
· floating-point numbers
· integer
· object
· string
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 at the time.
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)
The size of an integer is platform-dependent, although a maximum value of about 2 billion is the usual value (that's 32 bits signed).
Floating point numbers
Floating point numbers ("doubles") can be specified using any of the following syntaxes:
$a = 1.234; $a = 1.2e3;
The size of a floating point number is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (that's 64 bit IEEE format).
Warning
It is quite usual that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a little loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8 as the result of the internal representation really being something like 7.9999999999....
This is related to the fact that it is impossible to exactly express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3333333. . ..
So never trust floating number results to the last digit and never compare floating point numbers for equality. If you really need higher precision, you should use the arbitrary precision math functions or gmp functions instead.
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:
Escaped characters
sequence meaning
\n linefeed (LF or 0x0A in ASCII)
\r carriage return (CR or 0x0D in ASCII)
\t horizontal tab (HT or 0x09 in ASCII)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation
If you attempt to escape any other character, both the backslash and the character will be output. In PHP 3, a warning will be issued at the E_NOTICE level when this happens. In PHP 4, no warning is generated.
The second way to delimit a string uses the single-quote ("'") character. When a string is enclosed in single quotes, the only escapes that will be understood are "\\" and "\'". This is for convenience, so that you can have single-quotes and backslashes in a single-quoted string. Variables will not be expanded inside a single-quoted string.
Another way to delimit strings is by using here doc syntax ("<<<"). One should provide an identifier after <<<, then the string, and then the same identifier to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier used must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.
Here doc text behaves just like a double-quoted string, without the double-quotes. This means that you do not need to escape quotes in your here docs, but you can still use the escape codes listed above. Variables are expanded, but the same care must be taken when expressing complex variables inside a here doc as with strings.
Here doc string quoting example
$str = <<Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo {
var $foo;
var $bar;

function foo() {
$this->foo = 'Foo';
$this->bar = array('Bar1', 'Bar2', 'Bar3');
}
}

$foo = new foo();
$name = 'MyName';

echo <<My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

Note: Here doc support was added in PHP 4.
Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. Please see String operators for more information.
Characters within strings may be accessed by treating the string as a numerically-indexed array of characters, using C-like syntax. See below for examples.
Some string examples
/* Assigning a string. */
$str = "This is a string";

/* Appending to it. */
$str = $str . " with some more text";

/* Another way to append, includes an escaped newline. */
$str .= " and a newline at the end.\n";

/* This string will end up being '

Number: 9

' */
$num = 9;
$str = "

Number: $num

";

/* This one will be '

Number: $num

' */
$num = 9;
$str = '

Number: $num

';

/* Get the first character of a string */
$str = 'This is a test.';
$first = $str[0];

/* Get the last character of a string. */
$str = 'This is still a test.';
$last = $str[strlen($str)-1];
?>

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)
If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
echo "\$foo==$foo; type is " . gettype ($foo) . "
\n";
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. When you assign a value to an array variable using empty brackets, the value will be added onto the end of 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!
In PHP 3 it is not possible to reference multidimensional arrays directly within strings. For instance, the following will not have the desired result:
$a[3]['bar'] = 'Bob';
echo "This won't work: $a[3][bar]";
In PHP 3, the above will output This won't work: Array[bar]. The string concatenation operator, however, can be used to overcome this:
$a[3]['bar'] = 'Bob';
echo "This will work: " . $a[3][bar];
In PHP 4, however, the whole problem may be circumvented by enclosing the array reference (inside the string) in curly braces:
$a[3]['bar'] = 'Bob';
echo "This will work: {$a[3][bar]}";
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:

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

# Example 2:
$a = array(
"color" => "red",
"taste" => "sweet",
"shape" => "round",
"name" => "apple",
3 => 4
);
The array() function can be nested for multi-dimensional arrays:
$a = array(
"apple" => array(
"color" => "red",
"taste" => "sweet",
"shape" => "round"
),
"orange" => array(
"color" => "orange",
"taste" => "tart",
"shape" => "round"
),
"banana" => array(
"color" => "yellow",
"taste" => "paste-y",
"shape" => "banana-shaped"
)
);

echo $a["apple"]["taste"]; # will output "sweet"
?>
Objects
Object Initialization
To initialize an object, you use the new statement to instantiate the object to a variable.
class foo {
function do_foo() {
echo "Doing foo.";
}
}

$bar = new foo;
$bar->do_foo();
?>

Type Juggling
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().
If you would like to test any of the examples in this section, you can cut and paste the examples and insert the following line to see for yourself what's going on:
echo "\$foo==$foo; type is " . gettype ($foo) . "
\n";
Note: The behaviour of an automatic conversion to array is currently undefined.
$a = 1; // $a is an integer
$a[0] = "f"; // $a becomes an array, with $a[0] holding "f"
While the above example may seem like it should clearly result in $a becoming an array, the first element of which is 'f', consider this:
$a = "1"; // $a is a string
$a[0] = "f"; // What about string offsets? What happens?
Since PHP supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a?
For this reason, as of PHP 3.0.12 and PHP 4.0b3-RC4, the result of this automatic conversion is considered to be undefined. Fixes are, however, being discussed.
Type Casting
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.
$foo = 10; // $foo is an integer
$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:
$foo = (int) $bar;
$foo = ( int ) $bar;
It may not be obvious exactly what will happen when casting between certain types. For instance, the following should be noted.
When casting from a scalar or a string variable to an array, the variable will become the first element of the array:
$var = 'ciao';
$arr = (array) $var;
echo $arr[0]; // outputs 'ciao'
When casting from a scalar or a string variable to an object, the variable will become an attribute of the object; the attribute name will be 'scalar':
$var = 'ciao';
$obj = (object) $var;
echo $obj->scalar; // outputs 'ciao'
Wow its long article a I think, I will finish it for now in the next article we will talk about variable in PHP. See you

Comments :

0 komentar to “PHP Programing | PHP Basic | chapter 2 Language Reference”


Post a Comment

Please Report me if there's a dead link or invalid link in this post