一、一些重要的php版本
php 5.0引入面向对象
php5.3 引入命名空间
php7.0 性能优化
二、HHVM和Hack
HHVM本质上是一个虚拟机,将php代码转化为php字节码 ,大幅度提升性能。
就是作用类似用Zend引擎,但是HHVM支持PHP和Hack两种语言。
Hack相对于PHP,最显著的区别在于提供了静态类型的支持。
所以建议开发采用PHP7.0!!!
demo1:对应类型提示
<?php
// 强制类型声明为开启状态
// 当类型不一致时,程序报错
declare(strict_types=1);
// before php7
function test(array $arr)
{
foreach ($arr as $value) {
// ……
}
}
interface PayInterface
{
public function pay();
}
class Alipay implements PayInterface
{
public function pay()
{
echo 'alipay';
}
}
function test2(PayInterface $payMethod)
{
$payMethod->pay();
}
// 类的实例对象 is instanceof 接口名
// test2(new Alipay());
// after php7
function test3(int $a, int $b)
{
return $a + $b;
}
echo test3(3.14, 5);
demo:匿名类
<?php
// 匿名类
$obj = new class {
public $name = 'test';
public function getName()
{
return $this->name;
}
};
// var_dump($obj);
// echo $obj->getName();
class Outer
{
private $_name = 'outer';
public function test1()
{
return new class($this->_name) {
private $_trueName;
public function __construct($trueName)
{
$this->_trueName = $trueName;
}
public function test2()
{
return $this->_trueName;
}
};
}
}
$p1 = new Outer;
$p2 = $p1->test1();
echo $p2->test2();
生成器yield
(一)可以大大减少内存的消耗
(1)传统形式
echo memory_get_usage(),"\n";
$arr = range(1,1000000000);
echo memory_get_usage(),"\n";
(2)使用生成器
<?php
function xrange($start, $end)
{
for ($i=$start; $i <= $end; $i++) {
yield $i;
}
}
// 普通数组形式
echo memory_get_usage(), "\n";
$arr = range(1, 10000);
// $arr = xrange(1, 10000);
// var_dump($arr);exit;
foreach ($arr as $key => $value) {
//
}
echo memory_get_usage(), "\n";
(二)时间开销yield没有原生形式好。
<?php
function xrange($start, $end)
{
for ($i=$start; $i <= $end; $i++) {
yield $i;
}
}
// 普通数组形式
echo time(), "\n";
// $arr = range(1, 1000000);
$arr = xrange(1, 1000000);
foreach ($arr as $key => $value) {
//
}
echo time(), "\n";
(三)为什么时间慢,节省空间?
yield 返回的是迭代器对象不是数组,所以占据内存空间小。
(四)防范内存溢出
<?php
// 获取所有数据
// 普通方法
$sql = "select * from news";
$results = mysqli_query($sql);
while ($row = mysqli_fetch_assoc($results)) {
// 处理$row
}
// 改进yield方式
function getAllRecords()
{
$sql = "select * from news";
$results = mysqli_query($sql);
while ($row = mysqli_fetch_assoc($results)) {
yield $row;
}
}
$rs = getAllRecords();
foreach ($rs as $value) {
// $value
}
(五)协程工作
http://www.laruence.com/2015/05/28/3038.html
Homestead
详见参考手册