Basic knowledge:
Variable names must be $
identified by symbols
Naming conventions for variables:
1. Variable names must begin with a letter or underscore "_", such as "$_name", "$name", "$name 2", etc., but "$9name" is not correct.
2, the variable name can only be composed of letters, numbers, and "_", but also contain Chinese characters. such as "$_qq", "$QQ 308", "$my _apple", "such as" $name I Wait ", but" $name * "is wrong.
3. Variable names are not allowed to contain spaces. When the variable name consists of multiple words, it is recommended to use "_" to separate (such as $my _apple), commonly known as the underscore method, or start with a capital letter such as $myApple, commonly known as camel-named method (also known as the Hump name method
Memory_get_usage () Gets the current PHP occupied memory
Var_dump (); Get variable type
The Echo ("true") result is special when the output of the 1//Boolean variable is true and 1,false does not output anything
Integral type:
Integral type (integer): Similar to a common integer. It can be specified in decimal, octal, hexadecimal. Decimal is the daily use of numbers, octal, the number must be added "0" (this 0 is the Arabic numeral 0, not the English letter "ou" oh); hexadecimal, the number must be preceded by "0x"
String type:
1. The string type can be defined in three ways: single quote form, double quotation mark form, and heredoc structure form
2. When using strings, it is unavoidable to use the nesting between quotes, you can use the escape character "\"
3. When a variable is enclosed in double quotes, the variable is concatenated with the contents of the double quotation mark, and when the variable is included in the single quotation mark, the variable is treated as a string output
4. Use the delimiter to represent the string (<<<), then provide an identifier after "<<<" God (which can be defined by itself), then the string, and finally end the string with the provided identifier.
Special types:
Resources (Resource): resources are created and used by specialized functions, such as open files, data connections, and graphical canvases. we can manipulate resources (create, use, and release)
Examples are as follows:
<?php$file=fopen ("F.txt", "R"); Open file $con=mysql_connect ("localhost", "root", "root"); Connection Database $img=imagecreate (100,100);//Graphics Canvas?>
$a = fopen ("Open File Root", "R");//Open File
$b = fgets ($a);//Read the contents of the file
$c = fclose ($a);//Close file
The second type of special:
Null (NULL): null is a null type, is not case sensitive, the null type has only one value, which means that a variable has no value, when it is assigned null, or has not been assigned, or is unset (), the variable is considered NULL in three cases
Constants: Defined with define, with three parameters
BOOL Define (String $constant _name, mixed $value [, $case _sensitive = True])
The first parameter, "Constant_name", is a required parameter, a constant name, or a marker, and the name of the constant is consistent with the variable, but be aware that it does not have a dollar sign. The second parameter, "value," is a required parameter, which is the value of the constant. The third parameter, "Case_sensitive", is an optional parameter, specifying whether the case is sensitive, is set to true to be insensitive, the third parameter is not normally specified, the value of the default third parameter is False
System Constants (example):
1.__FILE__:p HP program file name. It can help us get the current file in the physical location of the server.
2.__line__:P The number of HP program file lines. It can tell us the current code in the first few lines.
3.php_version: The version number of the current parser. It can tell us the current PHP parser version number, we can know in advance whether our PHP code can be parsed by the PHP parser.
4.php_os: Executes the current PHP version of the operating system name. It can tell us the name of the operating system used by the server, we can optimize our code based on the operating system
There are two ways to take a value for a constant value:
1. The first is to get the value directly using the constant name
2. Second use of the constant () function: mixed constant (string constant_name)
Defined (string constants_name) gets whether the current constant name is defined and the return value is Boolean
Operator:
Arithmetic operators, assignment operators, comparison operators, ternary operators, logical operators, string join operators, error control operators
Assignment Operators (= and &):
The first one is to assign the value of the right expression to the left operand. It copies the value of the right expression to the left-hand operand. In other words, the left operand is first requested for a piece of memory, and then the copied value is placed in this memory.
The second is a reference assignment, meaning that both variables point to the same data. It will allow two variables to share a piece of memory, and if the data stored in this memory changes, then the values of the two variables will vary.
For example $c = & $a;
Comparison operator (! ===,=== (all equals, requires value is the same as type),<> (not equal to))
logical operators (with, or both, and,or,&&,| |, XOR (with only one value TRUE)!!! Different priority levels
Connectors:. and. = The former is to concatenate two strings, which is directly preceded by a string
Error control operator ' @ ': for some expressions that may fail during the run, we do not want to display an error message to the customer when an error occurs, which is unfriendly to the user. You can then place the @ before a PHP expression, and any error messages that the expression may produce are ignored
!!! It is important to note that the error control prefix "@" does not mask the parsing of the error information, it cannot be placed before the definition of a function or class, nor can it be used for conditional structures such as if and foreach
PHP (the Foreach loop is divided into two types:
1. Value only, do not remove the label
foreach (array as value) {}
2. Remove both the label and the value
foreach (array as subscript = = value)
Advanced Knowledge:
The definition of the array: $arr = Array ();//means creating an empty array and assigning the created empty array to the variable $arr.
1. Indexed array: $fruit = array("苹果","香蕉","菠萝");
Note that the keys of the array start from 0. You can use print_r($fruit);
statements to output array keys and their corresponding values
The first is to assign a value with the name of the array variable followed by a square bracket, and of course the key in the index array, in parentheses, must be an integer. Like what$arr[0]=‘苹果‘;
The second is to array()
create an empty array, use =>
symbols to separate the keys and values, the left side represents the key, and the right side represents the value. Of course, in an indexed array, the key must be an integer. Like whatarray(‘0‘=>‘苹果‘);
The third type: Use to array()
create an empty array, directly in the array in English single quotation marks ‘
or English double quotation marks "
, the array will default to establish a 0-based integer key. For example, array(‘苹果‘);
this array is equivalentarray(‘0‘=>‘苹果‘);
2. Associative arrays: Associative arrays are arrays of exponential groups whose keys are strings
The first is to assign a value with the name of an array variable followed by a square bracket, of course, the key in the associative array, in parentheses, must be a string. Like what$arr[‘apple‘]=‘苹果‘;
The second is to array()
create an empty array, use =>
symbols to separate the keys and values, the left side represents the key, and the right side represents the value. Of course, the key must be a string in the associative array. Like whatarray(‘apple‘=>‘苹果‘);
Custom functions:
1. Start with the keyword " function
"
2. The function name can begin with a letter or an underscore:function name()
3. Writing the function body in curly braces
Variable function: The calling method of a mutable function is the variable name parentheses. 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 purposes, including callback functions, function tables, and so on.
Classes and objects:
Class Car { $name = ' car '; function GetName () { return $this->name; }}
$car = new car ();
echo $car->getname ();
You can also use variables to create
$className = ' Car ';
$car = new $className ();
echo $car->getname ();
The properties of the class: properties are public by default and can be accessed externally. Object operators typically access properties or methods of an object, and for static properties use:: Double-colon access
Class method: Using the keyword static decoration, called static method, the static method does not need to instantiate the object, can be directly called through the class name, the operator is a double colon:
Constructors and destructors (one that is called automatically when an object is created, and one that is automatically called when the object is destroyed)
Add constructors and destructors
function __construct () {
Print "constructor is called \ n";
}
function __destruct () {
The print "destructor is called \ n";
}
Static properties and methods can be called without instantiating the class, directly in the way they are used 类名::方法名
. Static properties do not allow objects to be called with an operator
Class Car { private static $speed = ten; public static function GetSpeed () { return self:: $speed; }} Echo Car::getspeed (); Calling a static method
Static methods can also be dynamically called through variables
$func = ' getspeed ';
$className = ' Car ';
echo $className:: $func (); Dynamically calling static method overloads
Overloads of the object:
Overloading in PHP refers to the dynamic creation of properties and methods, which are implemented by magic methods.
The overloads of a property are implemented by __set,__get,__isset,__unset to assign, read, or determine whether a property is set or destroyed, respectively, for a nonexistent property.
The role of clone is to copy. such as $b clone $a. Equivalent to $b opened up a separate memory space, but the content and $ A are identical. If $b = $a, the equivalent of two pointers points to the same space: that is = = = established
$str = serialize ($a); object is serialized into a string
$c = Unserialize ($STR); Deserializing objects
String:
The difference between a single quote and a double quote: The variable name can be identified in double quotes, but not in single quotation marks.
Remove whitespace from the end of the string:
PHP has three functions to remove whitespace from a string
1.trim removes a string at both ends of a space.
2.rtrim is to remove the right space of a string, where r is the abbreviation.
3.ltrim is to remove the left space of a string, where L is the abbreviation
The function of getting the length of the English string directly in PHP is strlen (), using the mb_strlen()
function to get the Chinese length in the string.
1. The Intercept function of the English string substr ()
Function Description: substr (string variable, start intercept position, intercept number)
2. Chinese string intercept function mb_substr ()
Function Description: Mb_substr (string variable, start intercept position, intercept number, page encoding)
PHP Lookup String Function strpos (): Function Description: Strpos (string to be processed, string to position, starting position of positioning [optional])
Replace the string, we need to use the PHP replacement functionstr_replace()
Function Description:str_replace(要查找的字符串, 要替换的字符串, 被搜索的字符串, 替换进行计数[可选])
We need to use PHP's formatted string function sprintf ()
Function Description: sprintf (format, string to convert)
Return: Well-formed string
Example:
$STR = ' 99.9 '; $result = sprintf ('%01.2f ', $str); echo $result;//Results show 99.90
Merging and splitting of strings
1. Merging
PHP string Merge function implode () function Description: Implode (delimiter [optional], array), return value: Combine array elements into a single string
Example:
$arr = Array (' Hello ', ' world! '); $result = Implode (", $arr);p Rint_r ($result);//results show Hello world!
2. Segmentation
PHP string-delimited function explode (), function Description: Explode (delimiter [optional], string), return value: function returns an array of strings
Example:
$str = ' Apple,banana '; $result = explode (', ', $str);p Rint_r ($result);//Results Display array (' Apple ', ' banana ')
PHP string Escape function addslashes (), function Description: Used to add an escape character to a special character, returns a string
Cookies
Cookies are data stored in the client's browser, and we use cookies to track and store user data. In general, cookies are returned from the server to the client via HTTP headers
The most common method of cookies is to use the Setcookie function, Setcookie has 7 optional parameters, we commonly use the top 5:
1.name (COOKIE name) can be accessed via $_cookie[' name ')
2.value (value of the cookie)
3.expire (expiry time) UNIX timestamp format, default = 0, indicating that the browser is off and is invalidated
4.path (valid path) if the path is set to '/', the entire site is valid
5.domain (valid domain) the entire domain name is valid, if ' www.imooc.com ' is set, it is only valid in WWW subdomain
The deletion of cookies in PHP is also implemented using the Setcookie function: Setcookie (' Test ', ', Time ()-1);
Session
It is very simple to use the session in PHP, first execute the Session_Start method to open session, and then through the global variable $_session session read and write
Use session or cookie to store user information:
<?php
Session_Start ();
Assuming the user is logged on successfully, the following user data is obtained
$userinfo = Array (
' UID ' = 10000,
' Name ' = ' spark ',
' Email ' = ' [email protected] ',
' Sex ' = ' man ',
' Age ' = ' 18 '
);
Header ("content-type:text/html; Charset=utf-8 ");
/* Save the user information to the session */
$_session[' uid '] = $userinfo [' uid '];
$_session[' name '] = $userinfo [' name '];
$_session[' userinfo '] = $userinfo;
* A simple way to save user data to a cookie */
$secureKey = ' IMOOC '; Encryption key
$str = serialize ($userinfo); Serialization of user information
Before user information is encrypted
$str = Base64_encode (Mcrypt_encrypt (mcrypt_rijndael_256, MD5 ($secureKey), $str, MCRYPT_MODE_ECB));
After user information is encrypted
Store encrypted user data in a cookie
Setcookie (' UserInfo ', $str);
Decrypt when needed for use
$str = Mcrypt_decrypt (mcrypt_rijndael_256, MD5 ($secureKey), Base64_decode ($STR), MCRYPT_MODE_ECB);
$uinfo = Unserialize ($STR);
echo "Decrypted user information:<br>";
Print_r ($uinfo);
The simplest function to read a file is file_get_contents, which can read the entire file into a string
UNIX Timestamp (English is called: timestamp) it represents the sum of the seconds from January 1, 1970 00:00:00 to the current time.
PHP provides built-in function Strtotime implementation: Gets the timestamp of a date, or gets the timestamp of a time: Strtotime (the time string to parse, the timestamp of the computed return value "default is the current time, optional")
GD refers to the graphic device,php of the GD library is used to process graphics extension library, through the GD Library provides a series of APIs, you can process the image or directly generate new pictures
Exception (Exception handling) has several basic properties and methods, including the following:
Message content for exception messages
Code exception Codes
File name that throws an exception
Line throws an exception in the number of lines of the file
PHP Database Extensions:
1.mysql How to extend a database connection:
$link = mysql_connect (' mysql_host ', ' mysql_user ', ' Mysql_password ');
2.mysqli Extensions:
$link = Mysqli_connect (' mysql_host ', ' mysql_user ', ' Mysql_password ');
3.PDO expansion
$dsn = ' mysql:dbname=testdb;host=127.0.0.1 '; $user = ' dbuser '; $password = ' Dbpass '; $dbh = new PDO ($DSN, $user, $password);
PHP Development Notes