


One article explains in detail the features of each version of PHP5-8 [Summary]
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!
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();
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
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));
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'];
}
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) { // ... }
PHP5.2
JSON
- json_encode — JSON encoding of variables
- json_decode — Decoding of JSON formatted strings
PHP5.3
Namespace
Avoid conflicts between class names or variable names in different packages<?php namespace XXX; // 命名空间的分隔符是反斜杠,该声明语句必须在文件第一行。
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");
New magic methods__callStatic()and
__invoke()
##__callStatic(): Called when calling an inaccessible method in static mode
: The response method when calling an object by calling a function <pre class="brush:php;toolbar:false">$person = new Person('小明'); // 初始赋值
$person(); //触发__invoke()</pre>
<h3 id="strong-新增魔术变量-code-DIR-code-strong"><strong>新增魔术变量<code>__DIR__
获取当前执行的PHP脚本所在的目录
如当前执行的PHP文件为 /htdocs/index.php,则__FILE__
等于’/htdocs/index.php’,而__DIR__
等于’/htdocs’。
动态调用静态方法
public static function test($userName) { //... } $className = 'cls'; $className::test('Tom'); // PHP >= 5.3.0
延迟静态绑定
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()
class A { static public function callFuncXXOO() { print static::funcXXOO(); } // ... } B::callFuncXXOO(); //B::funcXXOO()
类外使用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 5.3开始,通过排除中间表达式,甚至可以进一步简化三元语句。 如果测试表达式在布尔上下文中评估为true,则返回其值。 否则,将返回替代方法。
<?php $favoriteColor = $_GET["color"] ?: "pink";
Phar
PHP5.3之后支持了类似Java的jar包,名为phar。用来将多个PHP文件打包为一个文件。
创建一个phar压缩包
$phar = new Phar('swoole.phar'); $phar->buildFromDirectory(__DIR__.'/../', '/.php$/'); $phar->compressFiles(Phar::GZ); $phar->stopBuffering(); $phar->setStub($phar->createDefaultStub('lib_config.php'));
使用phar压缩包
include 'swoole.phar'; include 'swoole.phar/code/page.php';
使用phar可以很方便的打包你的代码,集成部署到线上机器。
PHP5.4
Short Open Tag 短开放标签
自 PHP5.4 起总是可用。
//可以把 <?php echo $xxoo;?> //简写成: = $xxoo;?>
数组简写
// 原来的数组写法 $arr = array("key" => "value", "key2" => "value2"); // 简写形式 $arr = ["key" => "value", "key2" => "value2"];
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();
优先级
基类中的成员函数将被Traits中的函数覆盖,当前类中的成员函数将覆盖Traits中的函数。
内置 Web 服务器
PHP从5.4开始内置一个轻量级的Web服务器,不支持并发,定位是用于开发和调试环境。
在开发环境使用它的确非常方便。
php -S localhost:8000
动态访问静态方法
$func = "funcXXOO"; A::{$func}();
实例化时访问类成员
(new MyClass)->xxoo();
PHP5.5
yield关键字
yield关键字用于当函数需要返回一个迭代器的时候,逐个返回值。
function number10() { for($i = 1; $i <h3 id="strong-list-用于-foreach-strong"><strong>list() 用于 foreach</strong></h3><pre class="brush:php;toolbar:false">$array = [ [1, 2, 3], [4, 5, 6], ]; foreach ($array as list($a, $b, $c)) echo "{$a} {$b} {$c}\n";
细节修改
- 不推荐使用 mysql 函数,推荐使用 PDO 或 MySQLi
- 不再支持Windows XP.
- 可用 MyClass::class 取到一个类的完整限定名(包括命名空间)
- empty() 支持表达式作为参数
- try-catch 结构新增 finally 块
PHP5.6
常量增强
-
定义常量时允许使用之前定义的常量进行计算
const A = 2; const B = A + 1;
-
允许常量作为函数参数默认值
function func($arg = C::STR2)asdf
可变函数参数
用于代替 func_get_args()
function add(...$args) { //... }
同时可以在调用函数时,把数组展开为函数参数:
$arr = [2, 3]; add(1, ...$arr);
命名空间增强
命名空间支持常量和函数
PHP7.0
标量类型声明
四种标量类型:boolean (布尔型),integer (整型),float (浮点型, 也称作 double),string (字符串)
function typeString(string $a) { echo $a; } typeString('sad'); //sad
返回值类型声明
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 定义数组
define('ANIMALS', [ 'dog', 'cat', 'bird' ]); echo ANIMALS[1]; // 输出 "cat"
匿名类
匿名类就像一个没有事先定义的类,而在定义的时候直接就进行了实例化。
// 直接定义 $objA = new class{ public function getName(){ echo "I'm objA"; } }; $objA->getName();
null 合并运算符
$username = $_GET['user'] ?? 'nobody'; //这两个是等效的 当不存在user 则返回?? 后面的参数 $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
PHP7.1
可为空类型
参数以及返回值的类型现在可以通过在类型前加上一个问号使之允许为空。
当启用这个特性时,传入的参数或者函数返回的结果要么是给定的类型,要么是 null 。
<?php function testReturn(): ?string{ return 'elePHPant'; }
void类型
<?php function swap(&$left, &$right) : void{ //... }
多异常捕获
<?php try { // some code } catch (FirstException | SecondException $e) { // ... }
PHP7.2
新的对象类型object
<?php function test(object $obj) : object { return new SplQueue(); } test(new StdClass());
允许重写抽象方法
当一个抽象类继承于另外一个抽象类的时候,继承后的抽象类可以重写被继承的抽象类的抽象方法。
<?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
类属性支持类型声明
<?php class User { public int $id; public string $name; }
箭头函数
使用隐式按值作用域绑定定义函数的简写语法。
<?php $factor = 10; $nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]); // $nums = array(10, 20, 30, 40);?>
Null 合并运算符支持方法
<?php $array['key'] ??= computeDefault(); //if (!isset($array['key'])) {$array['key'] = computeDefault();} ?>
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);
注解
使用注解可以将类定义成一个一个低解耦,高内聚的元数据类。在使用的时候通过注解灵活引入,反射注解类实例的时候达到调用的目的。
注解类只有在被实例化的时候才会调用
联合类型
在不确定参数类型的场景下,可以使用
function printSomeThing(string|int $value) { var_dump($value); }
Match表达式
和switch cash差不多,不过是严格===匹配
<?php $key = 'b'; $str = match($key) { 'a' => 'this a', 'c' => 'this c', 0 => 'this 0', 'b' => 'last b', }; echo $str;//输出 last b
Nullsafe 运算符
//不实例 User 类,设置为null $user = null; echo $user->getName();//php8之前调用,报错 echo $user?->getName();//php8调用,不报错,返回空
构造器属性提升
在构造函数中可以声明类属性的修饰词作用域
<?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 ) {} }
推荐学习:《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!

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment