PHP Programming and Application _php tutorial

Source: Internet
Author: User
Tags arithmetic operators bitwise operators http authentication php programming processing instruction setcookie terminates variable scope
Chapter PHP3 Introduction

PHP is a server built-in script language that makes it possible to quickly develop dynamic web on UNIX.
PHP was conceived by Rasmus Lerdorf in the fall of 1994. The earliest unreleased version was the one he used to keep in touch with people who watched his online resume on his homepage. The first version of the delivery user was released in early 1995, and it was only used as a personal page authoring tool. It consisted of a very simple analysis engine with only a few macros and a set of tools for home page feedback (a guestbook, a counter, and some other things). In 1995, Rasmus rewritten the entire parser and named Php/fi 2. Fi comes from a software package that he writes to integrate data from another HTML form. He merges the personal page tools, form integration tools, and joins the support of the mSQL database, so there is php/fi. Php/fi then spread at an astonishing rate, and people began to use it extensively to write programs.
We cannot accurately count its scope of use, but according to the estimated end of 1996, there are already at least 15,000 sites in the world using Php/fil. By the year 1997, this number has grown to more than 50,000 sites. In the 1997, we also found a major twist in PHP's development process. This is the development of PHP from Rasmus personal hobby upgrades to a group of programmers who have organized work. Later, this parser was Zeev Suraski and Andi Gutmans rewrite, through this comprehensive rewrite, a large number of PHP/FI functions were transplanted into PHP3, and became the basic prototype of PHP3.
By 1998, there had been a large number of commercially available products, such as C2 's stronghold Web server and Redhat Linux bundled with PHP/FI parsers or PHP3 parsers, and based on Netcraft estimates of conservative data, PHP was already 150 in the world, 000 sites are used. With further analysis, we know that its use is much larger than the number of sites that use the Netscape Company's flagship product, an enterprise-class Web server. PHP3 a large number of C, Java and Perl language syntax, and added a variety of PHP own characteristics. One difference between it and a language such as JavaScript is that PHP3 is executed on the server and the client sees the result of its running on the server, which means that if you want to take PHP3 scrpit, you have to have WEB server support.
PHP3 supports HTTP authentication, cookie, GIF image creation, one of its most representative features is its database layer, which makes it very easy to write database-based Web pages. The databases currently supported are listed below:
Oracle, Sybase, MSQL, MySQL, Informix, Solid dBase, ODBC, Unix dbm, PostgreSQL, Adabas D,filepro velocis.

PHP3 also supports network programming with services that use protocols such as POP3, HTTP, SNMP, NNTP, and IMAP.
PHP3 Program Mode

There are three ways to get from HTML to PHP program mode:
The first method:

Such as:

The second method:

Such as:

The first method:

Such as:

Chapter II Variables

PHP3 supports the following types of variables:

(i), internal variables

There are mainly integers (interger), floating-point numbers (Float-point numbers), strings (string), arrays (array), objects (object).

1 Initializing variables

To initialize a variable in PHP, you simply assign it a value. For most types, this is the most straightforward. For arrays and objects, you can use other methods.

2 Initializing an array

An array can be assigned using one of two methods: using a series of sequential values, or by using the array () function (see section functions of the array).
To add successive values to an array, you simply assign the assignment to an array variable that is not marked. The value is added as the last element of the array into the array.

$names [] = "Jill"; $names [0] = "Jill"
$names [] = "Jack"; $names [1] = "Jack"

Similar to C, Perl, array subscripts start with 0.

3 Initializing objects

To initialize an object, create a variable of that type with the new statement.

class Foo {
function Do_foo () {
echo "Doing foo.";
$bar = new Foo;
$bar->do_foo ();

4 Variable Scope

The scope of a variable is its valid range. For most PHP variables there is only one scope. Local variable scopes are used in user-defined functions. The variables used within the function are set to local variables by default. For example:

$a = 1; /* Global scope */
Function Test () {
echo $a; /* Reference to local scope variable */
Test ();

This program does not output anything because the Echo statement outputs a local variable $a, and the $a within the function has never been assigned a value. You may notice that this is a little bit different from C, where a global variable can be referenced directly within a function, unless it is overridden by a local variable. This makes it possible for people to pay no attention to modifying the values of global variables. In PHP, the use of global variables within a function must be explicitly described. For example:

$a = 1;
$b = 2;
Function Sum () {
Global $a, $b;
$b = $a + $b;
Sum ();
Echo $b;

The above program will output "3". By declaring $ A and $b in the function as global variables, the variables you want to refer to are global. There is no limit to the number of global variables that a function can manipulate.
Another notable area of scope is the static variable. A static variable exists in the local function, but its value is not lost when the program leaves the function. Consider the following example:

Function Test () {
$a = 0;
echo $a;
$a + +;

This function is useless because it assigns $ A to 0 and then "0" on each invocation. The self-addition of $a++ has no effect because the variable $ A is freed after the function call ends. To make the Count program count without losing the current count result, $a to declare a static variable:

Function Test () {
static $a = 0;
echo $a;
$a + +;

Now, each time the test () function is called, it will hit a value of $ A and increase its value.

Static variables are essential when using recursive functions. A recursive function is a function that calls itself. Be very careful when writing recursive functions, because the number of cycles is uncertain. You must ensure that there are sufficient conditions to end the recursion process. The following is a simple recursive function that counts to 10:

Function Test () {
static $count = 0;
$count + +;
Echo $count;
if ($count < 10) {
Test ();

(b) Dynamic variables

Sometimes it is convenient to use variable variable names. That is, a variable name that can be dynamically assigned and used. An assignment statement for an ordinary variable such as:

$a = "Hello";

A dynamic variable refers to the value of the variable as the name of a new variable. In the example above, hello can be used as a variable name by double $. Cases:

$ $a = "world";

At this point, two variables are defined and stored in the PHP symbol tree: $a content is "Hello", $hello content is "world". Therefore, the statement: echo "$a ${$a}"; The display result is exactly the same as: echo "$a $hello";

(c) PHP external variables

1. HTML form (get and post)

When a form is submitted to PHP3 script, PHP automatically gets the variables in the form. For example:


When "submit" is pressed, PHP3 automatically generates the variable: $name, which contains all the content entered by the user.

2. IMAGE SUBMIT variable Name

When submitting a form, you can use the following markup to replace the standard submit button with a map:


When the user clicks on the graph, two additional variables, sub_x and sub_y, are sent to the server along with the form. It contains the coordinates at which the user clicked on the diagram. Experienced people may notice that the actual name given by the browser contains a period instead of an underscore, but PHP automatically converts the period to an underscore.

3. HTTP Cookies

PHP supports HTTP cookies. Cookies store data in the client browser to keep in touch with the user or to verify the identity of the user. You can use the Setcookie () function to set cookies. Cookies are part of the HTTP request header, so you must call the Setcookie () function before any output data is returned to the user's browser. It is similar to the limit of the Header () function. Any cookies returned by the client will be automatically converted to the standard PHP variable, just like the data from the Get and post methods.

If you want to set multiple values in a cookie, add [] to the name of the cookie, for example:

Setcookie ("mycookie[]", "testing", Time () +3600);

Note: The new cookie will overwrite the cookie already in your browser, unless they have a different path or domain.

4. Environment variables

PHP automatically converts the environment variable to a normal variable.

Echo $HOME; /* Shows the HOME environment variable, if set. */

Although information from get,post and cookie structures is automatically converted to PHP variables, it is best to explicitly read them from the environment variables to ensure that the correct values are obtained. You can use the getenv () function for this purpose. You can also set a variable by using the Putenv () function.

Variable type conversions
It is not necessary (and not supported) to make explicit type declarations in a variable definition, and the type of a variable depends on the type of its value. That is, if you assign a string value to variable Var, var becomes a string variable. If you assign an integer value to Var, it becomes an integer variable.

An example of a PHP automatic type conversion is the addition operator ' + '. If any one operand is of type double, all operands are evaluated as double, and the result is double type. Otherwise, all operands are computed by the integer type, and the result is an integer. Note: The type of the operand itself does not change, and the type transformation is done only at the time of calculation

$foo = "0"; $foo is a 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 + "Ten Little piggies"; $foo is a double (15)
$foo = 5 + "Ten Small Pigs"; $foo is an integer (15)

To change the type of the variable, you can also use the Settype () function.

1. Forced type conversion

Coercion type conversions in PHP are the same as in C: write the desired type name in parentheses before the variable that needs to be cast for the type.

$foo = 10; $foo is an integer
$bar = (double) $foo; $bar is a double
The allowable casts 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: The parentheses can contain tab or space, and the following function will be evaluated:

$foo = (int) $bar;
$foo = (int) $bar;

2. String conversion

When a string is evaluated as a numeric type, the value and type of the result are determined in the following manner.

If the string contains any '. ', ' e ', and ' e ' characters, it is evaluated as a double type. Otherwise, it is evaluated as an integer type.
The value is calculated from the beginning of the string. If the string is a valid number, the value is used, otherwise the value is 0. A valid number is a sign bit (optional) followed by one or several digits (also containing a decimal point) followed by an optional exponent. An exponent is an ' e ' or ' e ' followed by one or several numbers.

$foo = 1 + "10.5"; $foo is a double (11.5)
$foo = 1 + " -1.3e3"; $foo is a double (-1299)
$foo = 1 + "bob-1.3e3"; $foo is a double (1)
$foo = 1 + "BOB3"; $foo is an integer (1)
$foo = 1 + "Ten Small Pigs"; $foo is an integer (11)
$foo = 1 + "Ten Little piggies"; $foo is a double (11); The string contains ' E '

Chapter III Operators

I'll take a look at the arithmetic, string, logic, and comparison operators of PHP3, respectively.

1. Arithmetic operators

+: $a + $b plus $a plus $b
-: $a-$b minus $a minus $b
*: $a * $b multiply $a times $b
/: $a/$b except $a divided by $b
%: $a% $b modulo $a divided by the remainder of $b

If the two operands are integer values (the string is converted to an integer value), Division sign ("/") returns the integer value (the divisible value). If either operand is a floating-point value, do a floating-point division.

2 string operators

String operators have only string connectors (".").

$a = "Hello";
$b = $a. "World!"; Now $b = "Hello world!"

3. Assignment operators

The basic assignment operator is "=".

The value of an assignment expression is the value assigned to it. For example, the value of the expression $a = 3 is 3. This allows you to do some complicated things like this:

$a = ($b = 4) + 5; Now $a equals 9, $b is 4.

In addition to the basic assignment, there are "compound operators". For all binary numbers and strings, you are allowed to do variable self-compounding operations. For example:

=: $a = 3;
+ =: $a + = 5; Set $ A to 8, i.e. $a = $a + 5;
$b = "Hello";
. : $b. = "there!"; Set $b as "Hello there!", just like $b = $b. "There!";

4, bitwise operators

Bit operations allow you to set or reset the specified data.

&amp: With arithmetic, $a & $b with $a and $b, the result is set.
|: or arithmetic, $a | The result is set $b or $a or $b has a set position
~: Non-arithmetic, ~ $a non-$a not set the result is set

5. Logical operators

And: $a and $b with both $a and $b the true result is true
Or: $a or $b or $a or $b have a true result for true
XOR: True if $a xor $b different or $a and $b
! :  ! $a the non-$a false then the result is true
&&amp: $a && $b with $a and $b the true result is true
| |: $a | | $b or $a or $b have a true result for true

When comparing two variables, there are two operators for "and" and "or" which are different priorities for two operators

6. Comparison operators

The comparison operator, like a name, allows you to compare two values.

= =: $a = = $b equals $a equals $b result is true
! =: $a! = $b Not equal to $a not equal to $b result is true
<: $a < $b less than $a less than the result is true
>: $a > $b greater than $a greater than $b result is true
<=: $a <= $b less than or equal to $a less than or equal to $b result is true
>=: $a >= $b greater than or equal to $a greater than or equal to $b result is true

Fourth Chapter expressions

Expressions are the most important constituent elements of PHP. In PHP 3.0, almost everything you write is an expression. The simplest but most precise definition of an expression is "anything with a value".
A simple example is constants and variables. When you write "$a = 5", you assign the value ' 5 ' to the $a. (In this case, ' 5 ' is an shaping constant). In this case, you want to assign $a to a value of 5. So when you write $b = $a, the result you want is $b = 5. That is, $a is an expression with a value of 5.

A simple example of a complex expression is a function. For example, consider the following function:

function foo ()
return 5;

If you think that writing $c = foo () is actually the same as writing $c = 5, then you are right. A function is an expression whose value is the return value. Because Foo () returns 5, the value of the expression ' foo () ' is 5.

The value of PHP is certainly not limited to shaping, and is usually not. PHP supports three types of values: shaping values, floating-point values, and string values. PHP supports two mixed types (non-scalar): Arrays and objects. These two types of values can be assigned to variables or returned from functions.

PHP 3 is an expression-oriented language, so almost everything is an expression. Consider the example we have discussed, ' $a = 5 '. It is easy to see that there are two values, the value of the shaping constant ' 5 ', and the value of the variable that is also assigned to 5 $a. But there is actually an additional value, which is the value of the assignment statement itself. The value of the assignment statement itself is the assigned value, in this case 5. In fact, it means not considering what ' $a = 5 ' To do, it is an expression with a value of 5. In this way, write a statement such as ' $b = ($a = 5) ', just like ' $a = 5; $b = 5; ' (There is a semicolon at the end of each statement). Because the order of assignment is right-to-left you can also write ' $b = $a = 5 '.

Another good example of the direction of expression calculation is the addition, the addition and the first minus and then minus. Users of Php/fi and most other languages may be familiar with variable++ and variable--。 This is a self-adding and self-subtraction operation. In Php/fi 2, the statement ' $a + + ' has no value (it is not an expression), so you can neither assign it to it nor use it in any way. PHP 3 turns them into the same expression as in C, which enhances the ability to add and subtract. Similar to C, there are two types of self-----plus and post-add in PHP 3. The essence of the first plus and the post-addition is the variable self-addition, the function of the variable itself is the same. The difference is the value of the self-added expression. Shape as ' + + $variable ' first add, calculate the value of the variable since the addition (PHP first do the variable to add, and then read its value, it is called ' first Plus '). After adding the shape of ' $variable + + ', the value of the original variable $variable is computed before the self-addition ( PHP does self-add after reading the value of the variable, so it is called ' post-add '.

The most common expression is the comparison expression. This expression evaluates to 0 or 1, which means FALSE or TRUE, respectively. PHP Support > (greater than), >= (greater than or equal), = = (equals), < (less than) and <= (less than equals). This expression is usually used in conditional execution, such as an IF statement.

The last expression we want to discuss here is a mixed assignment expression. You already know that if you want to add a $a, you can simply write the word ' $a + + ' or ' + + $a '. But what if the value to be increased is greater than 1, such as adding 3 to it? You can write a few more ' $a + + ', but this is obviously not an efficient or receptive approach. Another common way is to write ' $a = $a + 3 '. Calculate the value of ' $a + 3 ' before assigning it back to the $a so that $a adds 3. In PHP 3, you can abbreviate it like in several other languages (for example, C), so that it's clearer and easier to understand. The current variable $a plus 3 can be written as ' $a + = 3 '. The meaning of this sentence is "take out the value of the $a, add it 3, in the $a". This, in addition to making the statement brief and clear, also makes it execute faster. The value of the expression ' $a + = 3 ', as well as a strict assignment statement, is the assigned value. Note: not 3, but the value of the $a plus 3 (which is assigned to $ A). Any double operator can be used for this assignment operation mode, such as ' $a-= 5 ' (variable $a minus 5), ' $b *= 7 ' (Variable $b multiplied by 7), and so on.

Finally, it is worth mentioning the truth value of the expression. Many times (mostly during conditional execution and looping), you don't care about the specific value of an expression, but just notice that it represents true or FALSE (PHP does not have a dedicated Boolean type). PHP uses a Perl-like method to calculate the true value of an expression. Any non-zero value is TRUE, and 0 is FALSE. Be sure to note that the negative zero value is a value of 0 and is considered TRUE! An empty string can be a string "0" for FALSE; The other string is TRUE. For non-quantity values (arrays and objects)-true if its value does not contain any elements that are FALSE.

Fifth Chapter PHP3 Language structure

(i), control structure

1. If statement

An If statement is an important feature in most languages, and it executes program segments based on conditions. The IF statement in PHP is similar to C:

if (expr)


As discussed in the expression, expr is computed as its true value. If expr is true, PHP executes the corresponding statement and, if False, ignores it.

If $ A is greater than $b, the following example shows ' A is bigger than B ':

if ($a > $b)

Print "A is bigger than B";

Typically, you want to execute more than one statement based on the condition. Of course, there is no need to add an IF judgment to each statement. Instead, multiple statements can be formed into a group of statements.
If statements can be nested within other if statements, allowing you to flexibly conditionally execute parts of the program.

2. Else statement

Usually you want to execute a statement when a particular condition is met, and the condition is to execute another statement. else is used to do this. ELSE extended if statement to execute another statement when the IF statement expression is false. For example, the following program executes if $a is greater than $b displays ' A is bigger than B ', otherwise ' A is not bigger than B ':

if ($a > $b) {
Print "A is bigger than B";
else {
Print "A is not bigger than B";

3. ElseIf statement

ELSEIF, as the name implies, is a combination of if and else, similar to else, that extends the IF statement to execute other statements when the IF expression is false. However, unlike else, it executes other statements only when the ElseIf expression is true.

You can use more than one ElseIf statement in an if statement. The first statement that ElseIf expression is true will be executed. In PHP 3, you can also write ' else if ' (written in two words) and ' ElseIf ' (written as a word) effect. This is just a small difference in writing (if you're familiar with C, it's also) and the result is exactly the same.

The ElseIf statement is executed only if the IF expression and any preceding ElseIf expression are false, and the current ElseIf expression is true.
The following is a nested-format if statement that contains ElseIf and else:

if ($a ==5):
Print "a equals 5";
Print "...";
ElseIf ($a ==6):
Print "a equals 6";
print "!!!";
Print "A is neither 5 nor 6";


4. While statement

The while loop is a simple loop for PHP 3. The same as in C. The basic format of the while statement is:

while (expr) statement

The meaning of the while statement is very simple. It tells PHP to repeatedly execute nested statements as long as the while expression is true. The value of the while expression is checked each time the loop starts, so even if it changes its value within the nested statement, the execution does not terminate until the loop ends (each time PHP runs a nested statement called a loop). Similar to the IF statement, you can enclose a set of statements in curly braces and execute multiple statements in the same while loop:

while (expr): statement ... Endwhile;

The following example is exactly the same, with the numbers 1 to 10:

/* Example 1 */
$i = 1;
while ($i <=10) {
Print $i + +; /* The printed value would be $i before the increment (post-
Increment) */

/* Example 2 */
$i = 1;
while ($i <=10):
Print $i;
$i + +;

5. Do. While statement

Do.. While is very similar to a while loop, it only checks that the expression is true at the end of each loop, not at the beginning of the loop. The main difference between it and the strict while loop is do. The first loop of the while is definitely executed (the truth expression is checked only at the end of the loop), without having to perform a strict while loop (the truth expression is checked at the beginning of each loop, and if False at first, the loop terminates execution immediately).

Do.. While loops have only one form:

$i = 0;
do {
Print $i;
} while ($i >0);

The above loop executes only once, because after the first loop, when the truth expression is checked, it calculates that it is FALSE ($i not greater than 0) loop execution terminates.

6. For Loop statement

The For loop is the most complex loop in PHP. The same as in C. The syntax for the For loop is:

for (EXPR1; expr2; expr3) statement

The first expression (EXPR1) is evaluated unconditionally (executed) at the beginning of the loop.
Each time the loop, the expression expr2 is computed. If the result is TRUE, the loop and nested statements continue to execute. If the result is FALSE, the entire loop ends.
At the end of each cycle, the EXPR3 is computed (executed). Each expression can be empty. Expr2 is empty, the number of cycles is variable (PHP defaults to True, like C). Don't do this unless you want to end the loop with a conditional break statement instead of a for truth expression.
Consider the following example. They all show numbers 1 through 10:

/* Example 1 */
for ($i =1; $i <=10; $i + +) {
Print $i;

/* Example 2 */
for ($i = 1;; $i + +) {
if ($i > 10) {
Print $i;

/* Example 3 */
$i = 1;
for (;;) {
if ($i > 10) {
Print $i;
$i + +;

Of course, the first example is obviously the best, but you can see that you can use an empty expression for many occasions in the For loop.
Other languages have a foreach statement to traverse an array or hash table. PHP uses the While statement and the list (), each () function to achieve this function.

7. Switch SELECT statement

A switch statement is like a series of if statements on the same expression. In many ways, you want to compare the same variable (or expression) with many different values and execute different program segments based on different comparisons. This is the use of the switch statement.

The following two examples do the same thing in different ways, one with a set of if statements, and the other with a SWITCH statement:

/* Example 1 */
if ($i = = 0) {
print "I equals 0";
if ($i = = 1) {
Print "I equals 1";
if ($i = = 2) {
Print "I equals 2";

/* Example 2 */
Switch ($i) {
Case 0:
print "I equals 0";
Case 1:
Print "I equals 1";
Case 2:
Print "I equals 2";

(b), require statement

The Require statement replaces itself with the specified file, much like the preprocessing #include in C.
This means that you cannot call the function to include the contents of different files each time, and put the require () statement in a looping structure. To do this, use the INCLUDE statement.

Require (' ');

(iii), include statements

The INCLUDE statement contains the specified file.
Each time you encounter an include, the include statement contains the specified file. So you can use the include statement in a looping structure to contain a series of different files.

$files = Array (' ', ' ', ' ');
for ($i = 0; $i < count ($files); $i + +) {
Include ($files [$i]);

(iv), function

Functions can be defined by the following syntax:

function foo ($arg _1, $arg _2, ..., $arg _n) {
echo "Example function.\n";
return $retval;

Any valid PHP3 code can be used in a function, or even the definition of another function or class

1. function return value

The function can return a value through an optional return statement. The return value can be any type, including lists and objects.

function My_sqrt ($num) {
return $num * $num;
Echo my_sqrt (4); Outputs ' 16 '.

A function cannot return more than one value at a time, but can be implemented by returning a list of methods:

function foo () {
Return Array (0, 1, 2);
List ($zero, $one, $two) = foo ();

2. Parameters

External information can be passed into the function through the parameter table, which is a series of comma-delimited variables and/or constants.
PHP3 is supported by the value shape parameter (default), variable parameters, and default parameters. Variable-length parameter tables are not supported, but can be implemented using the method of passing arrays.

3. Correlation parameters

The default function parameter is a pass-through method. If you allow the function to modify the value of the passed parameter, you can use the variable argument.
If you want the function to have a formal argument that is always a variable parameter, you can prefix the formal parameter with the (&) argument when the function is defined:

function foo (& $bar) {
$bar. = ' and something extra. ';
$str = ' This is a string, ';
Foo ($STR);
Echo $str; Outputs ' This is a string, and something extra. '

If you want to pass a mutable parameter to the default function (whose formal argument is not a variant), you can prefix the actual argument with the (&) when calling the function:

function foo ($bar) {
$bar. = ' and something extra. ';
$str = ' This is a string, ';
Foo ($STR);
Echo $str; Outputs ' This is a string, '
Foo (& $str);
Echo $str; Outputs ' This is a string, and something extra. '

4. Default value

The function can define a C + + style default value, as follows:

function Makecoffee ($type = "Cappucino") {
echo "Making a cup of $type. \ n";
Echo Makecoffee ();
echo Makecoffee ("espresso");

The output of this piece of code above is:

Making a cup of Cappucino.
Making a cup of espresso.
Note that when you use the default parameters, all parameters that have default values should be defined behind the parameters without default values, otherwise, they will not work as you would like.

5. Class (classes)

A class is a collection of a series of variables and functions. The class is defined with the following syntax:

    Class Cart {
var $items; Items in our shopping cart
ADD $num Articles of $ARTNR to the cart
function Add_item ($ARTNR, $num) {
$this->items[$artnr] + = $num;
Take $num articles of $artnr out of the cart
function Remove_item ($ARTNR, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr]-= $num;
return true;
} else {
return false;

The above defines a class called cart, which includes an associative array and two functions to add and remove items from the cart.
The class is the original model of the actual variable. You want to create a variable of the desired type by using the new operator.

$cart = new Cart;
$cart->add_item ("10", 1);

This establishes a cart class object $cart. The object's function Add_item () is called to add 1 to the 10th item.

Classes can be expanded from other classes. The extended or derived class has all the variables and functions of the base class and what you define in the extension definition. This is to use the extends keyword.

Class Named_cart extends Cart {
var $owner;
function Set_owner ($name) {
$this->owner = $name;

This defines a class named Named_cart that inherits all the variables and functions of the Cart class and adds a variable $owner and a function Set_owner (). The variables you set up for the Named_cart class can now set the owner of the carts. You can still use the generic cart function in the Named_cart variable:

$ncart = new Named_cart; Create a named Cart
$ncart->set_owner ("Kris"); Name that Cart
Print $ncart->owner; Print the CART owners name
$ncart->add_item ("10", 1); (Inherited functionality from cart)

A variable in a function $this means the current object. You need to access all the variables or functions of the current object using the form of $this->something.
A constructor in a class is a function that is called automatically when you create a new variable of a certain kind. A function in a class with the same name as a class is the constructor.

Class Auto_cart extends Cart {
function Auto_cart () {
$this->add_item ("10", 1);

This defines a class Auto_cart, which adds a constructor to the Cart class that sets item 10 for variable initialization each time the new operation is made. Constructors can also have parameters, which are optional, which makes them very useful.

Class Constructor_cart {
function Constructor_cart ($item = "ten", $num = 1) {
$this->add_item ($item, $num);
Shop the same old boring stuff.
$default _cart = new Constructor_cart;
Shop for Real ...
$different _cart = new Constructor_cart ("20", 17); true techarticle Chapter PHP3 Introduction PHP is a server built-in script language, which makes it possible to quickly develop dynamic web on UNIX as a reality. PHP was conceived by Rasmus Lerdorf in the fall of 1994 ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.