php_manual.doc

(2731 KB) Pobierz
PHP Manual

PHP Manual              - 499 -

PHP Manual

 

What is PHP?

PHP (officially "PHP: Hypertext Preprocessor") is a server-side HTML-embedded scripting language.

Simple answer, but what does that mean? An example:

Example 1-1. An introductory example

<html>

<head>

<title>Example</title>

</head>

<body>

<?php

echo "Hi, I’m a PHP script!";

?>

</body>

</html>

Notice how this is different from a CGI script written in other languages like Perl or C -- instead of writing a program with

lots of commands to output HTML, you write an HTML script with a some embedded code to do something (in this case,

output some text). The PHP code is enclosed in special start and end tags that allow you to jump into and out of PHP mode.

What distinguishes PHP from something like client-side Javascript is that the code is executed on the server. If you were to

have a script similar to the above on your server, the client would receive the results of running that script, with no way of

determining what the underlying code may be. You can even configure your web server to process all your HTML files

with PHP, and then there’s really no way that users can tell what you have up your sleeve.

 

 

Part II. Language Reference

Chapter 5. Basic syntax

 

Escaping from HTML

When PHP starts to handle file, it will just output the text it encounters. So if you have a HTML-file, and you change its

extension to .php, your file will keep working.

If you want to insert php-statements at some point in your file, you’ll need to indicate so to php, by entering "PHP mode"

in either of the following ways:

Example 5-1. Ways of escaping from HTML

1. <? echo ("this is the simplest, an SGML processing instruction\n"); ?>

<?= expression ?> This is a shortcut for "<? echo expression ?>"

2. <?php echo("if you want to serve XHTML or XML documents, do like this\n"); ?>

3. <script language="php">

echo ("some editors (like FrontPage) don’t

like processing instructions");

</script>

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.

Note: Support for ASP-style tags was added in 3.0.4.

The closing tag for the block will include the immediately trailing newline if one is present.

PHP allows you to use structures like this:

Example 5-2. Advanced escaping

<?php

if (boolean-expression) {

?>

<strong>This is true.</strong>

<?php

} else {

?>

<strong>This is false.</strong>

<?php}

?>

This works as expected, because PHP handles text within ?> and <?php as an echo() statement.

61.Chapter 5. Basic syntax

Instruction separation

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:

<?php

echo "This is a test";

?>

<?php echo "This is a test" ?>

Comments

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

<?php

echo "This is a test"; // This is a one-line c++ style comment

/* This is a multi line comment

yet another line of comment */

echo "This is yet another test";

echo "One Final Test"; # This is shell-style style comment

?>

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

<h1>This is an <?php # echo "simple";?> example.</h1>

<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.

<?php

/*

echo "This is a test"; /* This comment will cause a problem */

*/

?>

Chapter 6. Types

Introduction

PHP supports eight primitive types.

Four scalar types:

• boolean

• integer

• floating-point number (float)

• string

Two compound types:

• array

• object

And finally two special types:

• resource

NULL

Note: In this manual you’ll often find mixed parameters. This pseudo-type indicates multiple possiblities for that

parameter.

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. For

more information, see the section on Type Juggling.

Booleans

This is the easiest type. A boolean expresses a truth value. It can be either TRUE or FALSE.

Note: The boolean-type was introduced in PHP 4.

Syntax

To specify a boolean-literal, use either the keyword TRUE or FALSE. Both are case-insensitive.

$foo = True; // assign the value TRUE to $foo

Usually you use some kind of operator which returns a boolean value, and then pass it on to a control structure.

if ($action == "show_version") { // == is an operator which returns a boolean

echo "The version is 1.23";}

// this is not necessary:

if ($show_separators == true) {

echo "<hr>\n";}

// because you can simply type this:

if ($show_separators) {

echo "<hr>\n";}

Converting to boolean

To explicitly convert a value to boolean, use either the (bool) or the (boolean) cast. However, in most cases you do not

need to use the cast, since a value will be automatically converted if an operator, function or control structure requires a

boolean argument.

See also Type Juggling.

When converting to boolean, the following values are considered FALSE:

• the boolean FALSE

• the integer 0 (zero)

• the float 0.0 (zero)

• the empty string, and the string "0"

• an array with zero elements

• an object with zero elements

• the special value NULL

Every other value is considered TRUE (including any resource).

Warning

-1 is considered TRUE, like any other non-zero (whether negative or positive) number!

Integers

An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.

See also: Arbitrary precision integers and Floating point numbers

Syntax

Integers can be specified in decimal (10-based), hexadecimal (16-based) or octal (8-based) notation, optionally preceded

by a sign (- or +).

If you use the octal notation, you must precede the number with a 0 (zero), to use hexadecimal notation precede the

number with 0x.

Example 6-1. Integer literals

$a = 1234; # decimal number

$a = -123; # a negative number

$a = 0123; # octal number (equivalent to 83 decimal)

$a = 0x1A; # hexadecimal number (equivalent to 26 decimal)

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that’s 32

bits signed). PHP does not support unsigned integers.

Note: In PHP there is no such thing as integer division. 1/2 yields the float 0.5.

 

 

Integer overflow

If you specify a number beyond the bounds of the integer-type, it will be interpreted as a float instead.

$large_number = 2147483647;

var_dump($large_number);

// output: int(2147483647)

$large_number = 2147483648;

var_dump($large_number);

// output: float(2147483648)

// this goes also for hexadecimal specified integers:

var_dump( 0x80000000 );

// output: float(2147483648)

Furthermore, if some function or operator yields a number that is beyond the boundaries of integer, it will also be

automatically converted to float.

$million = 1000000;

$large_number = 50000 * $million;

var_dump($large_number);

// output: float(50000000000)

Warning

Unfortunately, there is a bug in the script engine (still present in 4.0.6, probably resolved in 4.0.7) so that

this does not always work correctly when there are negative numbers involved. For example: when you

do -50000 * $million, the result will be -429496728. However, when both operands are positive there

is no problem.

Converting to integer

To explicitly convert a value to integer, use either the (int) or the (integer) cast. However, in most cases you do not

need to use the cast, since a value will be autmatically converted if an operator, function or control structure requires a

integer-argument.

See also type-juggling.

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float

hasn’t got enough precision to give an exact integer result. No warning, not even a notice will be issued in this case!

Warning

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

echo (int) ( (0.1+0.7) * 10 ); // echoes 7!

See for more information the warning about float-precision.

 

 

From strings

See String conversion

From other types

Caution

Behaviour of converting to integer is undefined for other types. Currently, the behaviour is the same as if

the value was first converted to boolean. However, do not relay on this behaviour, as it can change

without notice.

Floating point numbers

Floating point numbers (AKA "floats", "doubles" or "real numbers") can be specified using any of the following syntaxes:

$a = 1.234; $a = 1.2e3; $a = 7E-10;

The size of a float 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).

Floating point precision

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

A string is series of characters. In PHP, a character is the same as a byte, that is, there are exactly 256 different characters

possible. This also implies that PHP has no native support of Unicode.

Note: It is no problem for a string to become very large. There is no practical bound to the size of strings imposed by

PHP, so there is no reason at all to worry about long strings.

Syntax

A string literal can be specified in three different ways.

• single quoted

• double quoted

• heredoc syntax

 

Single quoted

The easiest way to specify a simple string is to enclose it in single quotes (the character ’).

To specify a literal single quote, you will need to escape it with a backslash (\), like in many other languages. If a

backslash needs to occur before a single quote or at the end of the string, you need to double it. Note that if you try to

escape any other character, the backslash too will be printed! So usually there is no need to escape the backslash itself.

Note: In PHP 3, a warning will be issued at the E_NOTICE level when this happens.

Note: Unlike the two other syntaxes, variables will not be expanded when they occur in single quoted strings.

echo ’this is a simple string’;

echo ’You can also have embedded newlines in strings,

like this way.’;

echo ’Arnold once said: "I\’ll be back"’;

// output: ... "I’ll be back"

echo ’Are you sure you want to delete C:\\*.*?’;

// output: ... delete C:\*.*?

echo ’Are you sure you want to delete C:\*.*?’;

// output: ... delete C:\*.*?

echo ’I am trying to include at this point: \n a newline’;

// output: ... this point: \n a newline

Double quoted

If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:

Table 6-1. Escaped characters

sequence meaning

\n linefeed (LF or 0x0A (10) in ASCII)

\r carriage return (CR or 0x0D (13) in ASCII)

\t horizontal tab (HT or 0x09 (9) 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

Again, if you try to escape any other character, the backspace will be printed too!

But the most important pre of double-quoted strings is the fact that variable names will be expanded. See string parsing for

details.

Heredoc

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.

 

Warning

It is very important to note that the line with the closing identifier contains no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs after or before the semicolon.

Probably the nastiest gotcha is that there may also not be a carriage return (\r) at the end of the line, only a form feed, AKA newline (\n). Since Microsoft Windows uses the sequence \r\n as a line terminator, your heredoc may not work if you write your script in a Windows editor. However, most programming editors provide a way to save your files with a UNIX line terminator.

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.

Example 6-2. Here doc string quoting example

<?php

$str = "Example of string spanning multiple lines using heredoc syntax.";

 

class foo

{var $foo;

var $bar;

function foo()

{$this->foo = 'Foo';

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

}

$foo = new foo();

$name = 'Aleks Berdowicz';

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";

?>

Efekt:

My name is 'Aleks Berdowicz'. I am printing some Foo. Now, I am printing some Bar2. This should print a capital 'A': A

 

 

Note: Here doc support was added in PHP 4.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax, a simple one and a complex one. The simple syntax is the most common and convenient, it

provides a way to parse a variable, an array value, or an object property.

The complex syntax was introduced in PHP 4, and can by recognised by the curly braces surrounding the expression.

 

...

Zgłoś jeśli naruszono regulamin