One article explains in detail the features of each version of PHP5-8 [Summary]

青灯夜游
Release: 2023-04-11 07:06:01
forward
3913 people have browsed it

This article summarizes the features of each version of PHP5-8 for everyone. If necessary, take a look, collect and read. I hope it will be helpful to everyone!

One article explains in detail the features of each version of PHP5-8 [Summary]

Summary of features of each version of PHP5-8

PHP5.1:

  • autoload
  • PDO
  • MySQLi
  • Type constraints

PHP5.2:

  • JSON support

PHP5.3 :

  • Namespace
  • Anonymous function
  • Closure
  • New magic method__callStatic()and__invoke()
  • New magic variable__DIR__
  • Dynamic call to static method
  • Delayed static binding
  • Heredoc and Nowdoc
  • Use const to define constants outside the class
  • Ternary operator
  • Phar

PHP5.4:

  • Short Open Tag
  • Array abbreviation
  • Traits,
  • Built-in Web server
  • Dynamic access static method
  • Instantiation When accessing class members

PHP5.5:

  • yield
  • list is used for foreach
  • Details modification

PHP5.6:

  • Constant enhancement
  • Namespace enhancement
  • Variable function parameters

PHP7.0 :

  • Scalar type declaration
  • Return value type declaration
  • defined definition constant array
  • Anonymous class
  • null coalescing operation Symbol

PHP7.1:

  • Nullable type
  • void type
  • Multiple exception capture

PHP7.2:

  • New object object
  • Allows overriding abstract methods

PHP7.3: There is no big syntax change Changes

PHP7.4:

  • Type attribute
  • Arrow function
  • Null coalescing operator support method
  • Opcache pre Loading

PHP8.0:

  • JIT just-in-time compilation
  • Named parameters
  • Annotations
  • Union type
  • Match expression
  • Nullsafe operator
  • Constructor property promotion

PHP5.1


__autoload() magic method

This is an autoloading function. In PHP5, when we instantiate an undefined class When , this function will be triggered. You can enable automatic loading of classes 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();
Copy after login
  • Detailed explanation of __autoload() magic method in PHP

PDO

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

Installation

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

//Linux
extension=pdo.so
//Windows  
extension=php_pdo.dll
Copy after login

Use
<?php
$dbms=&#39;mysql&#39;;     //数据库类型
$host=&#39;localhost&#39;; //数据库主机名
$dbName=&#39;test&#39;;    //使用的数据库
$user=&#39;root&#39;;      //数据库连接用户名
$pass=&#39;&#39;;          //对应的密码
$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));
Copy after login

  • PHP PDO

MySQLi

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

The difference between mysql and mysqli:

  • Mysqli connection is a permanent connection, while mysql is a non-permanent connection.

  • Mysql connection will reopen a new process every time it is used for the second time. Mysqli connections always use 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'];
}
Copy after login

  • What is the difference between mysqli and mysql

Type constraints

Type constraints can limit the type of parameters, but this mechanism is not perfect and currently only applies to classes and callables (executable types) And array (array), not applicable to string and int.

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

PHP5.2


JSON

PHP5.3


Namespace

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

Anonymous function (closure)

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

New magic methods__callStatic()and__invoke()

##__callStatic()

: Called when calling an inaccessible method in static mode

__invoke()

: The response method when calling an object by calling a function <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">$person = new Person(&amp;#39;小明&amp;#39;); // 初始赋值 $person(); //触发__invoke()</pre><div class="contentsignin">Copy after login</div></div><h3><strong>新增魔术变量<code>__DIR__

获取当前执行的PHP脚本所在的目录

如当前执行的PHP文件为 /htdocs/index.php,则__FILE__等于’/htdocs/index.php’,而__DIR__等于’/htdocs’。

动态调用静态方法

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

$className = &#39;cls&#39;;
$className::test(&#39;Tom&#39;); // PHP >= 5.3.0
Copy after login

延迟静态绑定

PHP 5.3.0中增加了一个static关键字来引用当前类,即实现了延迟静态绑定。

这是因为 self 的语义本来就是“当前类”,所以 PHP5.3 给 static 关键字赋予了一个新功能:后期静态绑定

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()
Copy after login
class A
{
    static public function callFuncXXOO()
    {
        print static::funcXXOO();
    }
    // ...
}
B::callFuncXXOO(); //B::funcXXOO()
Copy after login

类外使用const定义常量

常量是一个简单的标识符。在脚本执行期间该值不能改变(除了所谓的魔术常量,他们其实不是常量)。常量默认大小写敏感。通常常量标识符总是大写的。

可以用define()函数来定义常量。在php5.3.0以后,可以使用const关键字在类定义的外部定义常量,先前版本const关键字只能在类(class)中使用。一个常量一旦被定义,就不能再改变或取消定义。

const和define的区别?

  • const是一个语言结构,而define是一个函数。const在编译时要比define快很多。

const用于类成员变量的定义,一经定义,不可修改。Define不可以用于类成员变量的定义,可用于全局常量。

  • Const可在类中使用,define不能

  • Const不能在条件语句中定义常量

  • const采用普通的常量名称,define可以采用表达式作为名称

  • const只能接受静态的标量,而define可以采用任何表达式

  • const定义的常量时大小写敏感,而define可以通过第三个参数(为true表示大小写不敏感)来指定大小写是否敏感。

  • PHP常量两种定义方法:define和const有什么区别

简化三元运算符

从PHP 5.3开始,通过排除中间表达式,甚至可以进一步简化三元语句。 如果测试表达式在布尔上下文中评估为true,则返回其值。 否则,将返回替代方法。

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

Phar

PHP5.3之后支持了类似Java的jar包,名为phar。用来将多个PHP文件打包为一个文件。

创建一个phar压缩包

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

使用phar压缩包

include 'swoole.phar';
include 'swoole.phar/code/page.php';
Copy after login

使用phar可以很方便的打包你的代码,集成部署到线上机器。

PHP5.4


Short Open Tag 短开放标签

自 PHP5.4 起总是可用。
//可以把
<?php echo $xxoo;?>
//简写成:  
<?= $xxoo;?>
Copy after login

数组简写

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

Traits

Traits是 PHP 多重继承的一种解决方案。PHP中无法进行多重继承,但一个类可以包含多个Traits
// Traits不能被单独实例化,只能被类所包含
trait SayWorld
{
    public function sayHello()
    {
        echo 'World!';
    }
}
class MyHelloWorld
{
    // 将SayWorld中的成员包含进来
    use SayWorld;
}

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

优先级

基类中的成员函数将被Traits中的函数覆盖,当前类中的成员函数将覆盖Traits中的函数。

内置 Web 服务器

PHP从5.4开始内置一个轻量级的Web服务器,不支持并发,定位是用于开发和调试环境。
在开发环境使用它的确非常方便。

php -S localhost:8000
Copy after login

动态访问静态方法

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

实例化时访问类成员

(new MyClass)->xxoo();
Copy after login

PHP5.5


yield关键字

yield关键字用于当函数需要返回一个迭代器的时候,逐个返回值。

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

list() 用于 foreach

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

细节修改

  • 不推荐使用 mysql 函数,推荐使用 PDO 或 MySQLi
  • 不再支持Windows XP.
  • 可用 MyClass::class 取到一个类的完整限定名(包括命名空间)
  • empty() 支持表达式作为参数
  • try-catch 结构新增 finally 块

PHP5.6


常量增强

  • 定义常量时允许使用之前定义的常量进行计算

    const A = 2;
    const B = A + 1;
    Copy after login
  • 允许常量作为函数参数默认值

    function func($arg = C::STR2)asdf
    Copy after login

可变函数参数

用于代替 func_get_args()

function add(...$args)
{
  //...
}
Copy after login

同时可以在调用函数时,把数组展开为函数参数:

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

命名空间增强

命名空间支持常量和函数

PHP7.0


标量类型声明

四种标量类型:boolean (布尔型),integer (整型),float (浮点型, 也称作 double),string (字符串)

function typeString(string $a)
{
    echo $a;
}
typeString(&#39;sad&#39;); //sad
Copy after login

返回值类型声明

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

define 定义数组

define(&#39;ANIMALS&#39;, [
    &#39;dog&#39;,
    &#39;cat&#39;,
    &#39;bird&#39;
]);
echo ANIMALS[1]; // 输出 "cat"
Copy after login

匿名类

匿名类就像一个没有事先定义的类,而在定义的时候直接就进行了实例化。

// 直接定义
$objA = new class{
    public function getName(){
        echo "I&#39;m objA";
    }
};
$objA->getName();
Copy after login

null 合并运算符

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

PHP7.1


可为空类型

参数以及返回值的类型现在可以通过在类型前加上一个问号使之允许为空。

当启用这个特性时,传入的参数或者函数返回的结果要么是给定的类型,要么是 null 。

<?php
  function testReturn(): ?string{
    return &#39;elePHPant&#39;;
  }
Copy after login

void类型

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

多异常捕获

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

PHP7.2


新的对象类型object

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

允许重写抽象方法

当一个抽象类继承于另外一个抽象类的时候,继承后的抽象类可以重写被继承的抽象类的抽象方法。

<?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;
}
Copy after login

PHP7.4


类属性支持类型声明

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

箭头函数

使用隐式按值作用域绑定定义函数的简写语法。

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

Null 合并运算符支持方法

<?php
  $array[&#39;key&#39;] ??= computeDefault();
  //if (!isset($array[&#39;key&#39;])) {$array[&#39;key&#39;] = computeDefault();}
?>
Copy after login

Opcache 预加载

Opcache将获取您的PHP源文件,将其编译为“ opcodes”,然后将这些编译后的文件存储在磁盘上。opcache会跳过源文件和PHP解释器在运行时实际需要之间的转换步骤。

PHP8.0


JIT即时编译

PHP8的JIT目前是在Opcache之中提供的

JIT在Opcache优化之后的基础上,结合Runtime的信息再次优化,直接生成机器码

JIT不是原来Opcache优化的替代,是增强

目前PHP8只支持x86架构的CPU

命名参数

就是具名参数,在调用函数的时候,可以指定参数名称,指定参数名称后,参数顺序可以不安装原函数参数顺序传
//传统方式调用
balance(100, 20);
//php8 使用命名参数调用
balance(amount: 100, payment: 20);
Copy after login

注解

使用注解可以将类定义成一个一个低解耦,高内聚的元数据类。在使用的时候通过注解灵活引入,反射注解类实例的时候达到调用的目的。
注解类只有在被实例化的时候才会调用

联合类型

在不确定参数类型的场景下,可以使用

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

Match表达式

和switch cash差不多,不过是严格===匹配

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

Nullsafe 运算符

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

构造器属性提升

在构造函数中可以声明类属性的修饰词作用域

<?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
        ) {}
    }
Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of One article explains in detail the features of each version of PHP5-8 [Summary]. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!