Modern PHP笔记

来源:互联网 发布:考研英语网络课 编辑:程序博客网 时间:2024/06/07 00:09

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!
0 0
原创粉丝点击