3

Summary

PHP5.1:

  • autoload
  • PDO
  • MySQLi
  • type constraints

PHP5.2:

  • JSON support

PHP5.3:

  • Namespaces
  • anonymous function
  • Closure
  • Added magic methods __callStatic() and __invoke()
  • Added magic variable __DIR__
  • Dynamically call static methods
  • lazy static binding
  • Heredoc and Nowdoc
  • Use const to define constants outside the class
  • Ternary operator
  • Phar

PHP5.4:

  • Short Open Tag
  • array shorthand
  • Traits,
  • Built-in web server
  • Dynamic access to static methods
  • Access class members at instantiation time

PHP5.5:

  • yield
  • list is used for foreach
  • detail modification

PHP5.6:

  • Constant enhancement
  • namespace enhancements
  • Variable function parameters

PHP7.0:

  • Scalar Type Declaration
  • return value type declaration
  • defined defines a constant array
  • anonymous class
  • null coalescing operator

PHP7.1:

  • nullable type
  • void type
  • Multiple exception catch

PHP7.2:

  • new object object
  • Allows overriding abstract methods

PHP7.3: no major changes at the syntax level

PHP7.4:

  • type attribute
  • arrow function
  • Null Coalescing Operator Support Methods
  • Opcache preload

PHP8.0:

  • JIT just-in-time compilation
  • named parameters
  • annotation
  • union type
  • Match expression
  • Nullsafe operator
  • Constructor property promotion

PHP5.1

__autoload() magic method

This is an autoload function, in PHP5, this function is triggered when we instantiate an undefined class. Autoloading of classes can be enabled by defining this function.
 function  __autoload($className) {  
    $filePath = “project/class/{$className}.php”;  
    if (is_readable($filePath)) {  
        require($filePath);  //这里可以只用require,因为一旦包含进来后,php引擎再遇到类A时,将不会调用__autoload,而是直接使用内存中的类A,不会导致多次包含。
    }  
}  
$a = new A();  
$b = new B();  
$c = new C();

Detailed explanation of __autoload() magic method in PHP

PDO

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for PHP to access databases.

Install

You can check whether the PDO extension is installed through PHP's phpinfo() function.

 //Linux
extension=pdo.so
//Windows  
extension=php_pdo.dll

use

 <?php
$dbms='mysql';     //数据库类型
$host='localhost'; //数据库主机名
$dbName='test';    //使用的数据库
$user='root';      //数据库连接用户名
$pass='';          //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";


try {
    $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
    echo "连接成功<br/>";
    /*你还可以进行一次搜索操作
    foreach ($dbh->query('SELECT * from FOO') as $row) {
        print_r($row); //你可以用 echo($GLOBAL); 来看到这些值
    }
    */
    $dbh = null;
} catch (PDOException $e) {
    die ("Error!: " . $e->getMessage() . "<br/>");
}
//默认这个不是长连接,如果需要数据库长连接,需要最后加一个参数:array(PDO::ATTR_PERSISTENT => true) 变成这样:
$db = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));

PHP PDO

MySQLi

mysqli.dll is an extension of PHP's support for new features of mysql, allowing access to functions provided by MySQL 4.1 and above.

The difference between mysql and mysqli:

  1. A mysqli connection is a permanent connection, while mysql is a non-persistent connection.
  2. Whenever a mysql connection is used for the second time, a new process will be reopened. mysqli connections always use only the same process.

use

 $conn = mysqli_connect('localhost', 'root', '123', 'db_test') or ('error');
$sql = "select * from db_table";
$query = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($query)){
    echo $row['title'];
}

What is the difference between mysqli and mysql

type constraints

The type of parameters can be restricted by type constraints, but this mechanism is not perfect, currently only applicable to classes and callable (executable types) and array (array), not applicable to string and int.

 // 限制第一个参数为 MyClass, 第二个参数为可执行类型,第三个参数为数组
function MyFunction(MyClass $a, callable $b, array $c)
{
    // ...
}

PHP5.2

JSON

PHP5.3

Namespaces

Avoid conflicting class or variable names in different packages
 <?php
namespace XXX; // 命名空间的分隔符是反斜杠,该声明语句必须在文件第一行。

Anonymous functions (closures)

Used to temporarily create an unnamed function for callback functions and other purposes.
 $func = function($arg)
{
    print $arg;
};
$func("Hello World! hovertree.top");

Added magic methods __callStatic() and __invoke()

__callStatic() : Called when an inaccessible method is called in static mode

__invoke() : the response method when calling an object by calling a function

 $person = new Person('小明'); // 初始赋值
$person(); //触发__invoke()

Added magic variable __DIR__

Get the directory where the currently executing PHP script is located

If the currently executed PHP file is /htdocs/index.php, then __FILE__ is equal to '/htdocs/index.php', and __DIR__ is equal to '/htdocs'.

Dynamically call static methods

 public static function test($userName)
{
    //...
}

$className = 'cls';
$className::test('Tom'); // PHP >= 5.3.0

lazy static binding

In PHP 5.3.0, a static keyword is added to refer to the current class, that is, delayed static binding is implemented.

This is because the semantics of self is originally "the current class", so PHP5.3 has given a new function to the static keyword: late static binding

 class A
{
    static public function callFuncXXOO()
    {
        print self::funcXXOO();
    }
    static public function funcXXOO()
    {
        return "A::funcXXOO()";
    }
}
class B extends A
{
    static public function funcXXOO()
    {
        return "B::funcXXOO";
    }
}
$b = new B;
$b->callFuncXXOO(); //A::funcXXOO()
 class A
{
    static public function callFuncXXOO()
    {
        print static::funcXXOO();
    }
    // ...
}
B::callFuncXXOO(); //B::funcXXOO()

Use const to define constants outside the class

A constant is a simple identifier. The value cannot be changed during script execution (except for so-called magic constants, which are not constants). Constants are case-sensitive by default. Usually constant identifiers are always uppercase.

Constants can be defined with the define() function. After php5.3.0, you can use the const keyword to define constants outside the class definition. In previous versions, the const keyword could only be used in classes. Once a constant is defined, it cannot be changed or undefine.

What is the difference between const and define?

  1. const is a language construct, and define is a function. const is much faster at compile time than define.

const is used for the definition of class member variables. Once defined, it cannot be modified. Define cannot be used for the definition of class member variables, it can be used for global constants.

  1. Const can be used in classes, define cannot
  2. Const cannot define constants in conditional statements
  3. const takes a normal constant name, define can take an expression as the name
  4. const can only accept static scalars, while define can take any expression
  5. Constants defined by const are case-sensitive, and define can specify case-sensitivity through the third parameter (true means case-insensitive).

Detailed explanation of PHP constants: the difference between define and const

Simplified ternary operator

As of PHP 5.3, ternary statements can be simplified even further by excluding intermediate expressions. Returns the value of the test expression if it evaluates to true in a boolean context. Otherwise, an alternative method will be returned.

 <?php
$favoriteColor = $_GET["color"] ?: "pink";

Phar

After PHP5.3, a Java-like jar package named phar is supported. Used to package multiple PHP files into one file.

Create a phar archive

 $phar = new Phar('swoole.phar');
$phar->buildFromDirectory(__DIR__.'/../', '/.php$/');
$phar->compressFiles(Phar::GZ);
$phar->stopBuffering();
$phar->setStub($phar->createDefaultStub('lib_config.php'));

Use phar archive

 include 'swoole.phar';
include 'swoole.phar/code/page.php';

Using phar can easily package your code, integrate and deploy to online machines.

php phar tutorial, tutorial on the use of phar package in PHP

Summary of new features and deprecated functions in PHP 5.3

Summary of new functions and new features of each version of PHP5

PHP5.4

Short Open Tag

Always available since PHP5.4.
 //可以把
<?php echo $xxoo;?>
//简写成:  
<?= $xxoo;?>

array shorthand

 // 原来的数组写法
$arr = array("key" => "value", "key2" => "value2");
// 简写形式
$arr = ["key" => "value", "key2" => "value2"];

Traits

Traits are a solution to PHP's multiple inheritance. Multiple inheritance is not possible in PHP, but a class can contain multiple Traits
 // Traits不能被单独实例化,只能被类所包含
trait SayWorld
{
    public function sayHello()
    {
        echo 'World!';
    }
}
class MyHelloWorld
{
    // 将SayWorld中的成员包含进来
    use SayWorld;
}

$xxoo = new MyHelloWorld();
// sayHello() 函数是来自 SayWorld 构件的
$xxoo->sayHello();

priority

Member functions in the base class will be overridden by functions in Traits, and member functions in the current class will override functions in Traits.

Introduction to Traits, a new feature of php5.4

Built-in web server

PHP has built-in a lightweight web server since 5.4, does not support concurrency, and is positioned for development and debugging environments.
It is really convenient to use it in a development environment.

 php -S localhost:8000

Dynamic access to static methods

 $func = "funcXXOO";
A::{$func}();

Access class members at instantiation time

 (new MyClass)->xxoo();

php5.4 summary

PHP5.5

yield keyword

The yield keyword is used to return values one by one when a function needs to return an iterator.

 function number10()
{
    for($i = 1; $i <= 10; $i += 1)
        yield $i;
}

list() for foreach

 $array = [
    [1, 2, 3],
    [4, 5, 6],
];
foreach ($array as list($a, $b, $c))
    echo "{$a} {$b} {$c}\n";

detail modification

  • mysql functions are deprecated, PDO or MySQLi are recommended
  • Windows XP is no longer supported.
  • The fully qualified name (including namespace) of a class can be obtained with MyClass::class
  • empty() supports expressions as arguments
  • A finally block has been added to the try-catch structure

PHP5.6

Constant enhancement

  1. When defining constants, allow computations with previously defined constants

     const A = 2;
    const B = A + 1;
  2. Allow constants as function parameter defaults

     function func($arg = C::STR2)asdf

Variable function parameters

Used in place of func_get_args()

 function add(...$args)
{
  //...
}

At the same time, you can expand the array into function parameters when calling the function:

 $arr = [2, 3];
add(1, ...$arr);

namespace enhancements

Namespaces support constants and functions

Summary of PHP5.6

PHP7.0

Scalar Type Declaration

Four scalar types: boolean (boolean), integer (integer), float (float, also known as double), string (string)

 function typeString(string $a)
{
    echo $a;
}
typeString('sad'); //sad

return value type declaration

 function returnErrorArray(): array
{
    return '1456546';
}
print_r(returnErrorArray());
/*
Array
Fatal error: Uncaught TypeError: Return value of returnArray() must be of the type array, string returned in 
*/

define defines an array

 define('ANIMALS', [
    'dog',
    'cat',
    'bird'
]);
echo ANIMALS[1]; // 输出 "cat"

anonymous class

An anonymous class is like a class that is not defined in advance, but is instantiated directly when it is defined.

 // 直接定义
$objA = new class{
    public function getName(){
        echo "I'm objA";
    }
};
$objA->getName();

PHP7 anonymous class usage

null coalescing operator

 $username = $_GET['user'] ?? 'nobody';
//这两个是等效的  当不存在user 则返回?? 后面的参数
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

PHP7.1

nullable type

The types of parameters and return values can now be made nullable by preceding the type with a question mark.

When this feature is enabled, the parameter passed in or the result returned by the function is either the given type or null.

 <?php
  function testReturn(): ?string{
    return 'elePHPant';
  }

void type

 <?php
  function swap(&$left, &$right) : void{
    //...
  }

Multiple exception catch

 <?php
try {
    // some code
} catch (FirstException | SecondException $e) {
    // ...
}

PHP7.2

new object type object

 <?php
 
function test(object $obj) : object
{
    return new SplQueue();
}
 
test(new StdClass());

Allows overriding abstract methods

When an abstract class inherits from another abstract class, the inherited abstract class can override the abstract methods of the inherited abstract class.

 <?php
 
abstract class A
{
    abstract function test(string $s);
}
abstract class B extends A
{
    // overridden - still maintaining contravariance for parameters and covariance for return
    abstract function test($s) : int;
}

PHP7.4

Class attributes support type declarations

 <?php
class User {
    public int $id;
    public string $name;
}

arrow function

Shorthand syntax for defining functions with implicit by-value scope binding.

 <?php
  $factor = 10;
  $nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
  // $nums = array(10, 20, 30, 40);?>

Null Coalescing Operator Support Methods

 <?php
  $array['key'] ??= computeDefault();
  //if (!isset($array['key'])) {$array['key'] = computeDefault();}
?>

Opcache preload

Opcache will take your PHP source files, compile them into "opcodes", and store these compiled files on disk. opcache skips the translation step between the source file and what the PHP interpreter actually needs at runtime.

Master the new features of each version of PHP 7.x

PHP7.0~PHP7.1~PHP7.2~PHP7.3~PHP7.4 New Features

PHP8.0

JIT just-in-time compilation

PHP8's JIT is currently provided in Opcache

On the basis of Opcache optimization, JIT optimizes again with the information of Runtime, and directly generates machine code

JIT is not a replacement for the original Opcache optimization, it is an enhancement

Currently PHP8 only supports CPUs with x86 architecture

named parameters

It is a named parameter. When calling a function, you can specify the parameter name. After specifying the parameter name, the parameter order can be passed without installing the original function parameter order.
 //传统方式调用
balance(100, 20);
//php8 使用命名参数调用
balance(amount: 100, payment: 20);

annotation

Using annotations, a class can be defined as a metadata class with low decoupling and high cohesion. When used, it is flexibly introduced through annotations, and the purpose of invocation is achieved when reflecting and annotating class instances.
Annotated classes are only called when they are instantiated

union type

In the case of uncertain parameter types, you can use

 function printSomeThing(string|int $value)
{
    var_dump($value);
}

Match expression

Similar to switch cash, but with strict === matching

 <?php
$key = 'b';
$str = match($key) {
    'a' => 'this a',
    'c' => 'this c',
     0  => 'this 0',
    'b' => 'last b',
  };
echo $str;//输出 last b

Nullsafe operator

 //不实例 User 类,设置为null
$user = null;
echo $user->getName();//php8之前调用,报错
echo $user?->getName();//php8调用,不报错,返回空

Constructor property promotion

The modifier scope of class properties can be declared in the constructor

 <?php
    // php8之前
    class User
    {
        protected string $name;
        protected int $age;
        public function __construct(string $name, int $age)
        {
            $this->name = $name;
            $this->age = $age;
        }
    }
    //php8写法,
    class User
    {
        public function __construct(
            protected string $name,
            protected int $age
        ) {}
    }

Explain the new features of PHP8 with examples


IT小马
1.2k 声望166 粉丝

Php - Go - Vue - 云原生