zfxcms ^回到顶部

您的当前位置:首页 > php资讯 > PHP基础 > php7整理-新增功能

php7整理-新增功能

所属分类: PHP基础   2020-03-23 11:13:32  编辑:admin  浏览次数 541 次

一、核心

       个人认为,标红的有点用

??举例:

之前版本写法:

$info = isset($_GET['email']) ? $_GET['email'] : ‘noemail';

PHP7版本的写法:

$info = $_GET['email'] ?? noemail;

还可以写成这种形式:

$info = $_GET['email'] ?? $_POST['email'] ?? ‘noemail';

使用实例

<?php    
// fetch the value of $_GET['user'] and returns 'not passed'    
// if username is not passed    
$username = $_GET['username'] ?? 'not passed';    
print($username);    
print("<br/>");    
// Equivalent code using ternary operator    
$username = isset($_GET['username']) ? $_GET['username'] : 'not passed';    
print($username);    
print("<br/>");    
// Chaining ?? operation    
$username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';    
print($username); 
?>

它产生以下浏览器输出 :

not passed
not passed 
not passed

< = >举例:

一个新的功能,空合并运算符(??)已被引入。它被用来代替三元运算并与 isset()函数功能结合一起使用。如果它存在并且它不是空的,空合并运算符返回它的第一个操作数;否则返回第二个操作数

<?php
   // fetch the value of $_GET['user'] and returns 'not passed'
   // if username is not passed
   $username = $_GET['username'] ?? 'not passed';
   print($username);
   print("<br/>");
   // Equivalent code using ternary operator
   $username = isset($_GET['username']) ? $_GET['username'] : 'not passed';
   print($username);
   print("<br/>");
   // Chaining ?? operation
   $username = $_GET['username'] ?? $_POST['username'] ?? 'not passed';
   print($username);
?>


这将在浏览器产生输出以下结果-

not passed
not passed
not passed


一个新的功能,飞船操作符已经被引入。它是用于比较两个表达式。当第一个表达式比第二个表达式分别小于,等于或大于它返回-1,0或1。

<?php
   //integer comparison
   print( 1 <=> 1);print("<br/>");
   print( 1 <=> 2);print("<br/>");
   print( 2 <=> 1);print("<br/>");
   print("<br/>");
   //float comparison
   print( 1.5 <=> 1.5);print("<br/>");
   print( 1.5 <=> 2.5);print("<br/>");
   print( 2.5 <=> 1.5);print("<br/>");
   print("<br/>");
   //string comparison
   print( "a" <=> "a");print("<br/>");
   print( "a" <=> "b");print("<br/>");
   print( "b" <=> "a");print("<br/>");
?>


这将在浏览器产生输出以下结果-

0
-1
1
0
-1
1
0
-1
1


                                             

比较是按照asc码来比的,如abcd 一直小于 b

 define() 函数

PHP7定义常量数组和匿名类

PHP7 常量数组

在 PHP7 中,如果您需要定义 Array 类型的常量,那么通过使用 define()函数进行定义是一个不错的选择。使用过 PHP 5.6 版本的朋友应该知道,在 PHP5.6 中,只能使用 const 关键字来定义数组类型的常量。 

常量数组实例

<?php
   //define a array using define function
   define('fruit', [
      'apple',
      'orange',
      'banana'
   ]);
   print(fruit[1]);
?>

它产生以下浏览器输出 :

orange

PHP7 匿名类

现在,您可以在 PHP7 中使用 new class 来定义(实例化)匿名类。匿名类可以用来代替完整的类定义。 

匿名类实例

<?php
   interface Logger {
      public function log(string $msg);
   }
   class Application {
      private $logger;

      public function getLogger(): Logger {
         return $this->logger;
      }

      public function setLogger(Logger $logger) {
         $this->logger = $logger;
      }  
   }
   $app = new Application;
   $app->setLogger(new class implements Logger {
      public function log(string $msg) {
         print($msg);
      }
   });

   $app->getLogger()->log("My first Log Message");
?>

它产生以下浏览器输出:


My first Log Message

可以将参数传递到匿名类的构造器,也可以扩展(extend)其他类、实现接口(implement interface),以及像其他普通的类一样使用 trait:

<?php
class SomeClass {}
interface SomeInterface {}
trait SomeTrait {}
var_dump(new class(10) extends SomeClass implements SomeInterface {
    private $num;

    public function __construct($num)
    {
        $this->num = $num;
    }
    use SomeTrait;
 });
?>

它产生以下浏览器输出:


object(class@anonymous)#1 (1) {

  ["Command line code0x104c5b612":"class@anonymous":private]=>

  int(10)

}

匿名类被嵌套进普通 Class 后,不能访问这个外部类(Outer class)的 private(私有)、protected(受保护)方法或者属性。 为了访问外部类(Outer class)protected 属性或方法,匿名类可以 extend(扩展)此外部类。 为了使用外部类(Outer class)的 private 属性,必须通过构造器传进来:

<?php
class Outer
{
    private $prop = 1;
    protected $prop2 = 2;

    protected function func1()
    {
        return 3;
    }

    public function func2()
    {
        return new class($this->prop) extends Outer {
            private $prop3;

            public function __construct($prop)
            {
                $this->prop3 = $prop;
            }

            public function func3()
            {
                return $this->prop2 + $this->prop3 + $this->func1();
            }
        };
    }
}
echo (new Outer)->func2()->func3();
?>

它产生以下浏览器输出:

6

unserialize()

PHP7引入了过滤 unserialize()函数以在反序列化不受信任的数据对象时提供更好的安全性。它可以防止可能的代码注入,使开发人员能够使用序列化白名单类。

示例

<?php
class MyClass1 {
   public $obj1prop;
}
class MyClass2 {
   public $obj2prop;
}
$obj1 = new MyClass1();
$obj1->obj1prop = 1;
$obj2 = new MyClass2();
$obj2->obj2prop = 2;
$serializedObj1 = serialize($obj1);
$serializedObj2 = serialize($obj2);
// default behaviour that accepts all classes
// second argument can be ommited.
// if allowed_classes is passed as false, unserialize converts all 
objects into __PHP_Incomplete_Class object
$data = unserialize($serializedObj1 , ["allowed_classes" => true]);
// converts all objects into __PHP_Incomplete_Class object except those of MyClass1 and MyClass2
$data2 = unserialize($serializedObj2 , ["allowed_classes" => ["MyClass1", "MyClass2"]]);
print($data->obj1prop);
print("<br/>");
print($data2->obj2prop);
?>

这将在浏览器产生以下输出 -

1
2

伪随机数产生器CSPRNG

在PHP7,以下两个新的函数引入以产生一个跨平台的方式加密安全整数和字符串。

·         random_bytes() - 生成加密安全伪随机字节。

·         random_int() - 生成加密安全伪随机整数。

random_bytes()

random_bytes()适合于使用来生成密码,密码学随机的任意长度的字符串,如:生成 salt,密钥或初始向量

string random_bytes ( int $length )

参数

·         length - 返回随机串的字节长度

返回值

  • 返回包含加密安全随机字节的请求数量的字符串。

错误/异常

  • 如果无法找到随机性的适当源,将引发异常

  • 如果给定参数无效,TypeError将被抛出

  • 如果给出字节长度无效,错误将被抛出

示例

<?php
$bytes = random_bytes(5);
print(bin2hex($bytes));
?>

这将在浏览器产生以下输出 -

54cc305593

random_int()

random_int()产生适合于用于结果是非常重要的加密随机整数。

语法

int random_int ( int $min , int $max )

参数

·         min - 返回最小值,它必须是PHP_INT_MIN或更大的值

·         max - 返回最大值,它必须是小于或等于PHP_INT_MAX

返回值

  • 返回最小值(min)到最大(max)的范围内,包括加密安全随机整数。

错误/异常

  • 如果无法找到随机性一个适当的源,将引发异常

  • 如果给定参数无效,TypeError 将被抛出

  • 如果 max 小于      min 时,错误将被抛出

示例

<?php
print(random_int(100, 999));
print("
");
print(random_int(-1000, 0));
?>

这将在浏览器产生以下输出 -

614
-882

 use 语句

从PHP7起,单次使用 use 语句可以用来从同一个命名空间导入类,函数和常量(而不用多次使用 use 语句)。

示例

<?php
// Before PHP 7
use com\yiibai\ClassA;
use com\yiibai\ClassB;
use com\yiibai\ClassC as C;
use function com\yiibai\fn_a;
use function com\yiibai\fn_b;
use function com\yiibai\fn_c;
use const com\yiibai\ConstA;
use const com\yiibai\ConstB;
use const com\yiibai\ConstC;
// PHP 7+ code
use com\yiibai\{ClassA, ClassB, ClassC as C};
use function com\yiibai\{fn_a, fn_b, fn_c};
use const com\yiibai\{ConstA, ConstB, ConstC};
?>

错误处理4

<?php
class MathOperations
{
   protected $n = 10;
   // Try to get the Division by Zero error object and display as Exception
   public function doOperation(): string
   {
      try {
         $value = $this->n % 0;
         return $value;
      } catch (DivisionByZeroError $e) {
         return $e->getMessage();
      }
   }
}
 
$mathOperationsObj = new MathOperations();
print($mathOperationsObj->doOperation());
?>


浏览器中将产生以下输出-

Modulo by zero


PHP7引入了intdiv()的新函数,它执行操作数的整数除法并返回结果为 int 类型。

示例

<?php
$value = intdiv(10,3);
var_dump($value);
print("
");
print($value);
?>

这将在浏览器产生以下输出 -

int(3)
3
Closure :: call - 绑定并调用闭包
Closure :: bind - 使用特定的绑定对象和类范围复制一个闭包
与 PHP5.6 的 bindTo 相比,PHP7 中的 Closure :: call()方法具有更好的性能,该方法被添加为临时将
对象范围绑定到闭包并调用它。

较早的 PHP 示例:
<?php
   class A {
      private $x = 1;
   }
   // Define a closure Pre PHP 7 code
   $getValue = function() {
      return $this->x;
   };

   // Bind a clousure
   $value = $getValue->bindTo(new A, 'A'); 

   print($value());
?>
它产生以下浏览器输出:

1
PHP7 及以上版本示例:
<?php
   class A {
      private $x = 1;
   }

   // PHP 7+ code, Define
   $value = function() {
      return $this->x;
   };

   print($value->call(new A));
?>
它产生以下浏览器输出:

1

PHP文章检索

PHP文章目录