php中后期静态绑定 关键字static
php后期静态绑定static
使用关键字static实现 通过这种机制 "static::"不再被解析为定义当前方法所在的类 在类的继承中 使用的类不再是当前类 而是调用类
self和static区别
self是根据所处的类去决定实例化对象
static是根据运行时调用的类去决定实例化对象
class A { public static function call() { $self = new self(); $static = new static(); $array = [$self, $static]; var_dump($array); } } class B extends A { } B::call(); //array(2) { // [0]=> // object(A)#1 (0) { // } // [1]=> // object(B)#2 (0) { // } //}
laravel中后期静态绑定的实现
<?php
class Model
{
public static function create(array $attributes = [])
{
$model = new static($attributes);
$model->save();
return $model;
}
public function firstOrCreate(array $attributes = [])
{
if (!is_null($instance = static::where($attributes)->first())) {
return $instance;
}
return static::create($attributes);
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接