PHP 5.0 to 7.1 common syntax sugars

Source: Internet
Author: User
Tags echo b throw exception
In computer science, grammatical sugars (syntactic sugar) refer to the syntax of a programming language that is easier to express an operation, which makes it easier for programmers to use the language: operations can become clearer, more convenient, or more consistent with programmers ' programming habits.

Type

Boolean

    • An empty object 4.0 is later consideredtrue

String

    • stringSimilar to the internal structure array , you can use subscript to access the string like Python

          $str = ' 012345 ';    echo $str [1];  1    echo $str {2};  2

Array

    • 5.4You can define the array later like JS

          $arr = [' One ', ' both ', ' three ']; It's a lot easier to feel

Global variables

Long time not always forget to re-organize a deeper impression

$_server

    • SERVER_ADDRIP address 127.0.0.1

    • SERVER_NAMEHost name localhost

    • SERVER_SOFTWAREServer Type Nginx

    • REMOTE_ADDRClient IP. 127.0.0.1
      S

$_files

    • $_FILES['file']['name']Picture original name

    • $_FILES['file']['type']Picture MIME type

    • $_FILES['file']['size']Picture size

    • $_FILES['file']['tmp_name']Server-Side Temp name

Constant

    • 5.3You can then use const to define constants

Const DEBUG = true;

Operator

    • <=>Comparison operators, which are 7.0 then supported

echo  $a <=> $b;/* When $a < $b, the expression returns 1 when $a = $b, the expression is returned 0 when $a > $b, the expression returns  1*/
    • ??An empty merge operator PHP7 attribute.

$name = $_post[' name ']?? '';  If the preceding value is not NULL, it returns itself, otherwise returns the value later
    • Ternary operators ?: 5.3 can be used later

$name = $_post[' name ']?: '; If the preceding value is not NULL, it returns itself, otherwise returns the value later

Process Control

    • goto5.3above valid

Operator can be used to jump to another location in the program. The target location can be marked with a colon for the target name, and the jump instruction is the mark after Goto followed by the target location. There are certain restrictions on Goto in PHP, where the target location can only be in the same file and scope, that is, you cannot jump out of a function or class method, or you can skip into another function. You cannot jump into any loop or switch structure. You can jump out of a loop or switch, usually using Goto instead of a multi-layered break.

Goto A;echo ' Foo '; A:echo ' bar;//Output Bar

Function

    • Variable length parameter ... , 5.6 available later

Function Dosum (... $arr) {    $sum = 0;    foreach ($arr as $v) {        $sum + = $v;    }    return $sum;} $arr = [1, 2, 3, 4, 5];echo dosum (... $arr);   Output 15echo dosum (1,2,3,4,5,6); Output 21//todo/** This syntax, I have been using it recently. The feeling is relatively simple. However, be aware of the server version: Recently entered a pit. */
    • anonymous function (Anonymous functions)5.3

Also called the closure function, is very common in JS. To prevent contamination from the global scope. PHP also supports this notation after 5.3.

$test = function ($name = ' Li ') {    echo ' My name is '. $name;}; $test ();

What to do if you want to inherit variables from the parent scope

Here a default output name is defined in the way $TPL = ' My name is ';//using use () to refer to the parent variable, the final output is consistent with the top $test = function ($name = ' Li ') used ($TPL) {    echo $ TPL. $name;}; $test ();

It is important to note that the parent scope of the closure function is the scope that defines it, not the scope of the call

Classes and objects

    • ::classA static method of the class that gets the fully qualified name of the class (including the namespace)

Namespace foo{    class test{    }    echo test::class;//output foo\test, when using namespaces is very useful}
    • 5.4A newly added multi-inheritance implementation method trait . Here's a summary of the basic concepts

class > trait > The inherited method of the parent class
3. Use insteadof to resolve Tarit conflict
4. Use as to modify the access control of the method
5. In the Code style= "font-size:14px;line-height:22px;padding:4px 2px 0px;" >trait can also use tarit . And in

Trait a {public    function say () {        echo ' trait  A ';    }} Trait b {Public    function say () {        echo ' trait B ';    }    Public Function Walk () {        echo ' walk B ';    }} Class Person {    use a, b{        B:: Say insteadof A;//using the Say method of B instead of the say method of a walk as        protected;    Set walk to Protected    } $obj = new person; $obj->say ();  echo trait A; $obj->walk (); Tip cannot access a protected method

6. In trait use, properties, static properties, static methods, abstract classes are all allowed.

Trait Test {public    static $obj;    public $name = 1;    static function Createobj () {        return empty (self:: $obj)? New self:self:: $obj;    }} Class Son {use    Test;} $obj = Son::createobj (); Echo $obj->name;  echo 1echo $obj = = = $obj 1? 0:1; Echo 1



    • 5.3Late static binding of a class
      The official explanation is:


This feature is named "Late static binding" from the perspective of the language itself. Late binding means that static:: It is no longer parsed to define the class in which the current method resides, but is calculated at the actual run time. It can also be called a "static binding" because it can be used (but not limited to) the invocation of a static method
At first glance, it seems that nothing can be understood. Look at the specific code.
class A {public static function who () {echo    __class__;    } public static function test () {self::who ();    }}class B extends A {public static function who () {echo __class__; }}b::test (); Echo a;//above is a normal call, output a//when we modify Class A's test method.    Change self to static after CLASS A {public static function who () {echo __class__;    } public static function test () {static::who ();    }}class B extends A {public static function who () {echo __class__; }}b::test (); echo B; 

Summary: PHP 5.3 Adds a new class of keywords that static can be called in the function's method. Use this keyword to achieve it 后期静态绑定 .

Exception handling

More Simple record
try{    throw new Execption (' throw exception '),} catch (Execption $e) {    //Get exception    $error = $e->getmessage ();} echo $error;  Throw exception

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.