Modern PHP笔记

1.Namespace

namespace Oreilly;
namespace Oreilly/ModernPHP;

2.Import and Alias

use Symfony\Component\HttpFoundation\Response;
$response = new Response('Oops',400);
$response->send();

or

use Symfony\Component\HttpFoundation\Response as Res;
$response = new Res('Oops',400);
$response->send();

As of PHP 5.6, it’s possible to import functions and constants.

use func Namespace\functionName;
functionName();
use constant Namespace\CONST_NAME;
echo CONST_NAME;

global namespace

namespace My\App;
class Foo
{ 
   public function doSomething()
   {
       throw new \Exception();
   }
}

3.Code to Interface

interface Documentable
{
    public function getId();
    public function getContent();
}
class HtmlDocument implements Documentable
{
//implement the interface...
}

4.Traits
Has in PHP 5.4, a trait is a partial class implementation that can be mixed into one or more existing PHP classes. Traits work double duty: they say what a class can do(like an interface), and the provide a modular implementation(like a class).

Define a trait
trait Geocodable{
 // define variables and methods
 }
Use a trait
class MyClass{
    use Geocodable;
}

5.Generator

function MakeRange($length){
    for($i = 0;$i<$length;$i++){
        yield $i;
    }
}
foreach(MakeRange(1000000) as $i){
    echo $i,PHP_EOL;
}

6.Closures

$closure = function ($name){
    return sprintf('Hello %s',$name);
};
echo $closure("Josh");// Hello Josh

or

$numbersPlusOne  = array_map(function ($number){
    return $number+1;
},[1,2,3]);
print_r($numbersPlusOne);// [2,3,4]
attach state

attach state to a PHP closure with the closure object’s bindTo() method or the use keyword.

function enclosePerson($name){
   return function ($doCommand) use ($name){
       return sprintf('%s,%s',$name,$doCommand);
   };
}
$clay = enclosePerson('Clay');
echo $clay('get me sweet tea!'); // Clay, get me sweet tea!
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值