Summary of key points and techniques of PHP development (i)

Source: Internet
Author: User
Tags apc arithmetic operators bitwise bitwise operators cryptographically secure fpm logical operators unpack

  • Opcache: Opcache originates from Zend optimizer+ renaming, the main role is to improve PHP performance by storing PHP script precompiled bytecode into shared memory, the advantage of storing precompiled bytecode is to save every time to load and parse PHP Scripting costs, but has no effect on I/O overhead such as reading and writing disk files, reading and writing databases, etc. The Opcache is likely to replace the APC location, although there is no user cache capability like APC. In addition, Opcache may conflict with similar components such as Eaccelerator, XCache, or APC.
  • php-fpm Process Pool : FastCGI processes Manager's master process is resident memory, creating and managing multiple processes dynamically in a process pool, effectively controlling memory and processes and smoothing overloaded PHP configurations. Ability to restart and restore damaged opcode in the event of an unexpected situation. Refer to my article PHP-FPM process Pool quest.
  • data type : PHP supports 9 types of raw data:
    Four types of scalar: 1. Boolean (Boolean) 2. Integer (integer) 3. Float (floating-point, also called Double) 4. String (string) of three composite types: 1. Array (arrays) 2. Object 3. Callable (callable) is the last of two special types: 1. Resource (Resource) 2. NULL (no type)
  • lambda Expressions (anonymous functions) and closures: Lambda expressions (anonymous functions) implement one-time, pollution-free function definition, which is an abandoned function and does not maintain any type of state. Closures increase the interaction of variables with the external environment on the basis of anonymous functions, byuseThe external environment variable to import is specified in the
    functionGetclosure ($n){      $a= 100; return function($m) Use($n, &$a) {             $a+=$n+$m; Echo $a." \ n "; };}$FN= Getclosure (1);$FN(1);//102$FN(2);// the$FN(3);//109Echo $a;//notice:undefined Variable
    classdog{Private $_name; protected $_color;  Public function__construct ($name,$color)    {         $this->_name =$name; $this->_color =$color; }      Public functionGreet$greeting)    {         return function() Use($greeting) {            //classes in which closures can be imported by $this variables            Echo"$greeting, I am a {$this->_color} dog named {$this->_name}.\n ";    }; }         Public functionswim () {return Static function() {             //A static closure in a class cannot be imported by $this variable, because the object does not have to be imported into a closure.
    So you can save a lot of memory, especially if you have many closures that don't require this functionality. Echo"Swimming....\n"; }; } Private functionPrivatemethod () {Echo"You had accessed to {$this->_name} ' s Privatemethod (). \ n"; } Public function__invoke () {//This method allows the object itself to be called as a closure Echo"I am a dog!\n"; }} $dog=NewDog ("Rover", "Red");$dog->greet ("Hello")();$dog-swim () ();$dog();//the closure is dynamically created by Reflectionclass, Reflectionmethod, and a direct call to the non-public method is implemented. $class=NewReflectionclass (' Dog ');$closure=$class->getmethod (' Privatemethod ')->getclosure ($dog);$closure();
  • single/double quotes, Heredoc, Nowdoc: Single quote string only need to escape the single quotation mark (\ '), backslash (\ \), the rest is output; the variables in the double-quote string are parsed; the HEREDOC structure resembles a double-quote string ; Nowdoc is similar to the single quote string, the NOWDOC structure and the HEREDOCS structure use the same tag <<<, but the following identifiers are enclosed in single quotes, i.e. <<< ' EOT '
  • string Variable parsing : Can be divided into $ parsing and {} parsing. $ parsing is a valid variable that resolves a $ lead, and {} parsing is a variable derived from parsing {}
  • SQL injection Risk : The following is an enumeration
    1. Addslashes function Escape risk: For the URL parameter arg =%df\ ' after addslashes escaped after GBK encoding arg = ' 2. UrlDecode function decoding risk: for URL parameter uid = 1%2527 after calling UrlDecode function decoding (two decoding) will become UID = 1 '
  • Case Conversion :
    $str Preg_replace_callback (    '/([a-z]*) ([a-z]*)/',     function($matchs) {        return Strtoupper ($matchs[1]). Strtolower ($matchs[2]);    },     $str);
  • Binary Security : The C string is terminated with a null character (' s '), which makes the C string unable to hold binary data such as pictures, audio, video, compressed files, and vice versa, which is called binary security. This concept is often mentioned in PHP and is only a simple explanation here. Here is the implementation of the Redis simple dynamic string (SDS), which is binary safe:
    File path: src/sds.hstruct sdshdr {    //record the number of bytes used in the BUF array,    int len;        Record the number of unused bytes in the BUF array    int free;        A byte array used to hold the string    char buf[];};
  • /and% and * * operator : the operand of the modulo operator% is converted to an integer before the operation (except for the fractional part), and the result of the modulo operator % is the same as the dividend symbol (sign), * * denotes the exponentiation operation
    5/3; // 1.66666666666675.7% 3; // 25% 3; // 22 * * 3; // 8
  • Operator Precedence: Priority descending from top to bottom
    Combination Direction operator Additional Information
    No Clone new Clone and New
    Left [ Array ()
    Right ** Arithmetic operators
    Right ++ -- ~ (int) (float) (String) (Array) (object) (BOOL) @ Type and increment/decrement
    No instanceof Type
    Right ! logical operators
    Left * / % Arithmetic operators
    Left + - . Arithmetic operators and string operators
    Left << >> Bitwise operators
    No < <= > >= Comparison operators
    No == != === !== <> <=> Comparison operators
    Left & Bitwise operators and references
    Left ^ Bitwise operators
    Left | Bitwise operators
    Left && logical operators
    Left || logical operators
    Left ?? Comparison operators
    Left ? : Ternary
    Right = += -= *= **= /= .= %= &= |= ^= <<= >>= Assignment operators
    Left and logical operators
    Left Xor logical operators
    Left Or logical operators
  • unset () and NULL: Deleting a reference, triggering the corresponding variable container refcount minus one, but the behavior in the function depends on the type of variable you want to destroy, such as unset a global variable, only the local variable is destroyed, and the variable in the calling environment (including the variable passed by the Function argument reference) will remain calledthe same value as before unsetThe unset variable assigns a value of NULL to the variable, and the variable is assigned null directly to the corresponding variable container refcount = 0
    //Example one: destroying a global variable within a function $foo is not validfunctionDestroy_foo () {Global $foo; unset($foo); Echo $foo;//notice:undefined Variable:foo}$foo= ' Bar ';d Estroy_foo ();Echo $foo;//bar//Example two: to unset a global variable in a function, use the $GLOBALS array to implement thefunctionfoo () {unset($GLOBALS[' Bar ']);}$bar= "Something"; foo ();Echo $bar;//notice:undefined Variable:bar
  • Pack () and unpack () : These two functions can be used as the binary string encoding/decoding function of socket programming
     $ BinaryData  = pack  ("nvc*", 0x1234, 0x5678, N/a); // pack data into binary string  $ Array  = unpack  ("C4chars/nint", $ BinaryData ); // unpack data from binary string  print_r  ( $array );  //array ([chars1] [chars2] = [CHARS3] = [CHARS4] [int] = 16706)  
  • php7-group use usage :

     //  proposed group use syntax:  use  foolibrary\bar\baz\{ClassA, ClassB, ClassC, CLASSD as   Fizbo};  //  Compared to current use syntax:  Span style= "COLOR: #0000ff" >use   Foolibrary\bar\baz\classa;  use   FOOLIBRARY\BAR\BAZ\CLASSB;  use   FOOLIBRARY\BAR\BAZ\CLASSC;  use  FOOLIBRARY\BAR\BAZ\CLASSD as  fizbo; 
  • php7-null merge operator (??)
    // fetches the request parameter user and results in ' nobody ' if it doesn ' t exist $username $_get [' User ']?? ' Nobody '; // equivalent to: $username = isset ($_get[' user ') "$_get[' user ']: ' nobody ';
  • PHP7-Merge comparison operator (<=>) ($a <=> $b) = = = 0
    operator <=> equivalent
    $a < $b ($a <=&G T $b) = = = 1
    $a <= $b ($a <=> $b) = =-1 | | ($a <=> $b) = = = 0
    $a = = $b
    $a! = $b ($a <=> $b)!== 0
    $a >= $b ($a <=> $b) = = = 1 | | ($a <=> $b) = = = 0
    $a > $b ($a <=> $b) = = = 1
  • PHP7-user layer random number generator : More secure and convenient
     1. random_bytes (int length): Generates cryptographically secure Pseudo-Random bytes, such as when generating salts, keys or initialization vectors. 2. Random_int (int min, int max): Generates cryptographically secure pseudo-random Integers, such as when shuffling a D Eck of Cards for a poker game. 
      $bytes  = random_bytes (5 var_dump  (bin2hex  ( $bytes )); // string (Ten) "385e33f741"  var_dump  (Random_int (100, 999)); // int (248)  
  • Php7-declare (strict_type=1): PHP7 added 4 scalar type declarations of int, float, string, and bool, declare (strict_ type=1) will make PHP not automatically convert the data type, which makes PHP a strongly typed language. DECLARE (strict_type=1) must be the first statement of a file, affecting only all function calls within the current file, without affecting other files that it contains (through include, etc.).

  • PHP7-Catch error: PHP7 implements a global Throwable interface, and the original exception and part of the error implement this interface. There is more error in PHP7 to be captured exception returned to the developer, error if not captured.

Summary of key points and techniques of PHP development (i)

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.