PHP 语法

匿名函数

匿名函数也叫做闭包函数 即不指定名称的函数 常用作回调函数参数的值

匿名函数演示一

$values = array('first','second','third');

array_map(function($para){
	echo $para;
	echo "<br>";
}, $values);

## 输出 
## first
## second
## third 

匿名函数演示二

$myPrint = function($msg){
	echo $msg;
	echo "<br>";
};

$myPrint("hello world");

## 输出 hello world

匿名函数演示三 使用外部定义变量

$name = "Json";

$myPrint = function($msg) use($name){
	echo $msg." ".$name;
	echo "<br>";
};

$myPrint("hello");

## 输出 hello Json

后期静态绑定

在类的继承过程中 使用的类不再是当前类 而是调用的类 使用关键字 static来实现 "static::function()" 不再被解析为定义当前方法所在的类 而是在实际运行时计算得到的

静态方法演示

class A {
    public static function call() {
        echo __CLASS__;
        echo "<hr>";
    }
    public static function test() {
    	self::call();
        static::call();
    }
}

class B extends A {
    public static function call() {
        echo __CLASS__;
        echo "<hr>";
    }
}

B::test();

## 输出
## A
## ----------
## B

非静态方法演示

class A {
    public function call() {
        echo __CLASS__;
        echo "<hr>";
    }
    public function test() {
    	self::call();
        static::call();
    }
}

class B extends A {
    public function call() {
        echo __CLASS__;
        echo "<hr>";
    }
}

B::test();
static会根据运行时调用的类来决定实例化对象 而self是根据所在位置的类来决定实例化对象

反射

主要是用来动态的获取系统中的类 实例对象 方法等信息
class People
{
    private $name   = 'Json';
    private $age    = 20;

    //Constructor
    public function __construct()
    {
        //Constructor
    }

    //print variable one
    public function getName()
    {
        echo $this->name."
";
    }

    //print variable two
    public function getAge()
    {
        echo $this->age."
";
    }
}

$reflector = new ReflectionClass('People');
print_r($reflector->getProperties());

## 输出 Array ( [0] => ReflectionProperty Object ( [name] => name [class] => People ) [1] => ReflectionProperty Object ( [name] => age [class] => People ) )


print_r($reflector->getMethods());
##输出 Array ( [0] => ReflectionMethod Object ( [name] => __construct [class] => People ) [1] => ReflectionMethod Object ( [name] => getName [class] => People ) [2] => ReflectionMethod Object ( [name] => getAge [class] => People ) )

trait

由于PHP是单继承的语言 但是又想实现代码复用的功能 就可以使用trait。trait不能像类一样进行实例化 而是通过关键字use添加到其它类的内部
trait sayHello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait sayWorld {
    public function sayWorld() {
        echo 'World';
    }
}

class myHelloWorld {
    use sayHello, sayWorld;
    public function say() {
        echo '!!!';
    }
}

$say = new MyHelloWorld();
$say->sayHello();
$say->sayWorld();
$say->say();

## 输出 Hello World!!!
原文地址:https://www.cnblogs.com/alin-qu/p/8366603.html