PHP Language Summary

Source: Internet
Author: User
Tags object serialization string back
PHP Language Summary: Basic syntax type constant operator Process Control function class and object namespace super global variable garbage collection mechanism


1 Basic Syntax
*php Mark
echo "Hello World";
... more code
echo "last Statement";
The script ends with no PHP end tag

Note: If the file content is pure PHP code, it is best to remove the PHP end tag at the end of the file.
This avoids having to accidentally add a space or line break after the PHP end tag, which causes PHP to start outputting these blanks.
There is no intent to output at this time in the script.

* Detach from HTML

This would show if the expression is true.

Otherwise this'll show.


2 Types
* Introduction
PHP supports 8 types of raw data.

Four types of scalar:
Boolean (Boolean)
Integer (integer type)
Float (floating-point, also called double)
String (String)

Two kinds of composite types:
Array (arrays)
Object (Objects)

Finally, there are two special types:
Resource (resources)
NULL (no type)

Note: Look at the value and type of the expression, use the Var_dump () function, get the type with GetType (), and determine if it is a type Is_type ()

*boolean
To specify a Boolean value, use the keyword TRUE or FALSE. Two are not case sensitive

When converted to Boolean, the following values are considered FALSE:
The Boolean value FALSE itself
Integer value 0 (0)
Floating-point value 0.0 (0)
An empty string, and the string "0"
An array that does not include any elements
Var_dump ((BOOL) ""); BOOL (FALSE)
Var_dump ((bool) 1); BOOL (TRUE)
Var_dump ((BOOL)-2); BOOL (TRUE)
Var_dump ((bool) "foo"); BOOL (TRUE)
Var_dump ((bool) 2.3e5); BOOL (TRUE)
Var_dump ((BOOL) array (12)); BOOL (TRUE)
Var_dump ((bool) array ()); BOOL (FALSE)
Var_dump ((BOOL) "false"); BOOL (TRUE)
?>

*integer
The maximum value can be represented by a constant php_int_max.

*float
*string
Single quotes: does not parse the variables inside
Double quotes: Parses the variables inside
(if there are no variables then it is recommended to use single quotes so that the efficiency will be higher because there is no need to parse the contents)
Complex (curly braces): Simply write the expression as if it were outside the string, then enclose it in curly braces {and}.
Valid, when using multiple arrays in a string, be sure to enclose it in parentheses.
echo "This works: {$arr [' foo '][3]}";
Effective
echo "This works:". $arr [' foo '][3];
?>

*array

Create a simple array
$array = Array (1, 2, 3, 4, 5);
Print_r ($array);
Now delete all of the elements, but keep the array itself unchanged:
foreach ($array as $i = = $value) {
Unset ($array [$i]);
}
Print_r ($array);
Delete entire array unset ($array)
?>
*object
To create a new object, instantiate a class using the new statement:

Class Foo
{
function Do_foo ()
{
echo "Doing foo.";
}
}
$bar = new Foo;
$bar->do_foo ();
?>
*resource
A resource is returned as a database connection
*null
A null type has only one value, which is a case-insensitive constant, NULL.
A variable is considered NULL in the following cases:
is assigned a value of NULL.
has not been assigned a value.
Be unset ().
Determine if NULL, use Is_null ()

2 Variables
* Basic
$this is a special variable that cannot be assigned a value
Variables are always assigned by default and reference variables, which means that changing the new variable will affect the original variable
* Pre-defined variables
* Variable Range
In a user-defined function, a local function scope is introduced. Any variables used inside the function will be limited to the local function by default
$a = 1; /* Global scope */
function Test ()
{
echo $a; /* Reference to local scope variable */
}
Test ();
?>
and C language is a little different, in C, global variables in the function automatically, unless overridden by local variables.
Global variables in PHP must be declared as globals when used in functions
$a = 1;
$b = 2;
function Sum ()
{
Global $a, $b;


$b = $a + $b;
}
Sum ();
Echo $b;
?>

The state variable exists only in the local function domain, but its value is not lost when the program executes away from this scope
function test ()
{
static $a = 0;
echo $a;
$a + +;
}
?>

* Variable variable
$a = ' Hello ';
$ $a = ' world ';
echo "$a ${$a}";
Output the exact same result as the following statement:
echo "$a $hello";
?>
* Variables from outside of PHP
$_post $_get

3 Constants
A valid constant name
Define ("FOO", "something");
Define ("FOO2", "something Else");
Define ("Foo_bar", "something More");
Illegal constant name
Define ("2FOO", "something");
The following definitions are legal, but should be avoided: (Custom constants do not start with __)
Maybe someday php will define a __foo__ magic constant.
This will conflict with your code.
Define ("__foo__", "something");
?>

4 operator
* Priority level
$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
Mixing + + + produces undefined behavior
$a = 1;
echo + + $a + $a + +; May print 4 or 5
?>
* ERROR operator
Supports an error control operator: @, any error messages that may be generated by the expression are ignored.
* Execute operator
Note that this is not a single quote! PHP will attempt to execute the contents of the anti-quote as a shell command and return its output information
The effect of using the inverse quote operator "'" is the same as the function shell_exec ().
$output = ' Ls-al ';
echo "
$output
";
?>
Result: Export the file directory structure to
* String Join operator
There are two strings (string) operators. The first one is the join operator (".") ), which returns the string after its left and right arguments are concatenated.
The second is the Join assignment operator (". ="), which attaches the right argument to the left argument
$a = "Hello";
$b = $a. "World!"; Now $b contains "Hello world!"
$a = "Hello";
$a. = "world!"; Now $a contains "Hello world!"
?>
* Array Operators
$a + $b Union of Joint $a and $b.
$a = = $b equal if the $a and $b have the same key/value pairs true.
$a = = = $b congruent if $a and $b have the same key/value pairs and the order and type are the same, TRUE.
$a! = $b is TRUE if the $a does not equal $b.
$a <> $b If the $a is not equal to $b true.
$a!== $b Not equal to TRUE if the $a is not all equals $b.

The + operator appends the array element on the right to the left array, and the key names in all two arrays are ignored on the right side of the array.
$a = Array ("A" = "Apple", "b" = "banana");
$b = Array ("A" = "pear", "b" = "Strawberry", "c" = "cherry");

$c = $a + $b; Union of $a and $b
echo "Union of \ $a and \ $b: \ n";
Var_dump ($c);

$c = $b + $a; Union of $b and $a
echo "Union of \ $b and \ $a: \ n";
Var_dump ($c);
?>

Cells in an array are equal if they have the same key name and value
$a = Array ("Apple", "banana");
$b = Array (1 = "banana", "0" = "apple");

Var_dump ($a = = $b); BOOL (TRUE)
Var_dump ($a = = = $b); BOOL (FALSE)
?>
* Type operator
Instanceof used to determine if a PHP variable belongs to an instance of a class
Class MyClass
{
}

Class Notmyclass
{
}
$a = new MyClass;


Var_dump ($a instanceof MyClass);
Var_dump ($a instanceof notmyclass);
?>

V: Process Control
*if Else
* Process Control instead of syntax
PHP provides some alternative syntax for process control, including If,while,for,foreach and switch.
The basic form of an alternative syntax is to replace the left curly brace ({) with a colon (:) and the right curly brace (})
Endif;,endwhile;,endfor;,endforeach; and Endswitch;.


A is equal to 5


*while
while (expr):
Statement
...
Endwhile;

* FOR
$people = Array (
Array (' name ' = ' Kalle ', ' salt ' = 856412),
Array (' name ' = ' Pierre ', ' salt ' = 215863)
);

for ($i = 0, $size = sizeof ($people); $i < $size; + + $i)
{
$people [$i] [' salt '] = rand (000000, 999999);
}
?>

*foreach
You can easily modify the elements of an array by adding & to it before $value.
This method assigns a value to a reference instead of copying a value.
$arr = Array (1, 2, 3, 4);
foreach ($arr as & $value) {
$value = $value * 2;
}
$arr is now Array (2, 4, 6, 8)
Unset ($value); Finally, remove the reference
?>
*require and include
Require error is to stop the script, include will produce a warning
Require_once and require basically, the only difference is that PHP checks whether the file
has been included, if yes it will not be included again.

Six Functions
* Variable function
mutable functions are similar to mutable variables
This means that if a variable name has parentheses after it, PHP will look for a function with the same name as the value of the variable and try to execute it.
Variable functions can be used to implement some uses, including callback functions, function tables.
function foo () {
echo "in Foo ()
\ n ";
}

function bar ($arg = ") {
echo "in Bar (); Argument was ' $arg '.
\ n ";
}

Use Echo's wrapper function
function Echoit ($string)
{
Echo $string;
}

$func = ' Foo ';
$func (); This calls Foo ()

$func = ' Bar ';
$func (' Test '); This calls bar ()

$func = ' Echoit ';
$func (' Test '); This calls Echoit ()
?>
* Anonymous function
echo Preg_replace_callback (' ~-([A-z]) ~ ', function ($match) {
return Strtoupper ($match [1]);
}, ' Hello-world ');
Output HelloWorld
?>

Seven classes and objects
* Basic Concepts
$this is a reference to the calling object (usually the object to which the method is subordinate)
* Properties
Inside a member method of a class, you can access a non-static property by using the (object operator): $this->property, where property is the name of the attribute.
A static property is accessed by:: (Double-colon): Self:: $property. More static properties vs. non-static
* Class Constants
You can define a value that always remains constant in a class as a const
Class MyClass
{
CONST CONSTANT = ' constant value ';
}
?>
* Auto Load Class
*static Static keyword
Declaring a class property or method as static can be accessed directly without instantiating the class. Static properties cannot be accessed through an object that is instantiated by a class (but static methods can)
Because static methods are loaded before they are compiled, all non-static methods cannot be accessed because they do not yet exist
* Abstract class
Any class, if at least one of its methods is declared abstract, then the class must be declared abstract
* Interface
Using interfaces (interface), you can specify which methods a class must implement, but you do not need to define the specifics of these methods.
*traits
Trait is similar to a class, but only designed to combine functionality in a fine-grained and consistent way.
Trait cannot be instantiated by itself. It adds a combination of horizontal characteristics to the traditional inheritance;
In other words, the members of the application class do not need inheritance.
Trait Ezcreflectionreturninfo {
function Getreturntype () {/*1*/}
function Getreturndescription () {/*2*/}
}

Class Ezcreflectionmethod extends Reflectionmethod {
Use Ezcreflectionreturninfo;
/* ... */
}

Class Ezcreflectionfunction extends Reflectionfunction {
Use Ezcreflectionreturninfo;
/* ... */
}
?>
* Traversing objects
*final keywords
If a method in the parent class is declared final, the child class cannot overwrite the method. If a class is declared final, it cannot be inherited.
* Object Replication
* Object Comparison
When comparing two object variables using the comparison operator (= =), the principle of comparison is: if the properties and property values of the two objects are equal,
and two objects are instances of the same class, the two object variables are equal.


If you use the strict equality operator (= = =), the two object variables must point to the same instance of a class (that is, the same object).
* Late static binding
* Objects and references
One key point is "the object is passed by reference by default". But it's not exactly right. Here are some examples to illustrate.
* Object serialization
All values in PHP can be represented by using the function serialize () to return a string containing a stream of bytes. The Unserialize () function can re-change the string back to the original PHP value.
Serializing an object will save all of the object's variables, but will not save the object's methods, only the name of the class will be saved

Eight namespaces
* Namespace Overview
User-written code conflicts with the name of a class/function/constant or third-party class/function/constant inside PHP.
namespace My\name; Refer to the "Defining Namespaces" subsection

Class MyClass {}
function MyFunction () {}
Const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\myclass; Refer to the "Global Space" subsection

$a = strlen (' Hi '); Refer to the "Using namespaces: Fallback global Functions/Constants" subsection

$d = Namespace\myconst; Refer to the section "NAMESPACE Operators and __namespace__ constants"

$d = __namespace__. ' \myconst ';
ECHO constant ($d); Refer to "Namespaces and Dynamic Language Features" subsection
?>

*namespace keywords and __namespace__ constants
namespace MyProject;
Echo ' "', __namespace__, '"; Output "MyProject"
?>

* Global Space
If no namespace is defined, all classes and functions are defined in the global space,
Same as before PHP introduced the concept of namespaces. Precede the name with a prefix \ means that the name is
The name in the global space, even if the name is in a different namespace.
namespace a\b\c;

/* This function is A\b\c\fopen */
function fopen () {
/* ... */
$f = \fopen (...); Calling the global fopen function
return $f;
}
?>

Nine Super Global variables
$GLOBALS
$_server
$_get
$_post
$_files
$_cookie
$_session
$_request
$_env

10 garbage collection mechanism
* Reference counters, each PHP variable is stored in a variable container called "Zval", in addition to the type and value of the variable,
Also includes two bytes of extra information, the first of which is "Is_ref" is a bool value used to identify whether it belongs to a reference collection
The second extra byte is refcount for the count of citations
$a = "new string";
Xdebug_debug_zval (' a ');
?>
Result: A: (Refcount=1, is_ref=0) = ' new String '
* If a reference count increases it will continue to be used, if the reference count is reduced to 0, the variable container will be Bai Qing 0 (free)
  • 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: info-contact@alibabacloud.com 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.