PHP5.3_延迟静态绑定_static

基于PHP版本: 5.3.5

PHP5.3 以后引入了延迟静态绑定:

static(关键字) 类似于 self(关键字) , 但它指向的是被调用的类(Document而不是包含类(DomainObject) static 和 self 的区别:

Code:

<?php
class DomainObject{
	public static function createStatic(){
		return new static();		
	}
	public static function createSelf(){
		return new self();
	}
}

class User extends DomainObject{
	
}

class Document extends DomainObject{
	
}

echo '<pre>';
var_dump( Document::createStatic());
var_dump( Document::createSelf());

Result:

object(Document)[1]
object(DomainObject)[1]

 

以前你这么写:

abstract class DomainObject{

}

class User extends DomainObject{
	public static function create(){
		return new User();
	}
}

class Document extends DomainObject{
	public static function create(){
		return new Document();
	}
}

现在, 你可以这么写: 

abstract class DomainObject{
	public static function create(){
		return new static();
	}
}

class User extends DomainObject{

}

class Document extends DomainObject{

}

好处: 可以节省大量重复代码~

 

 

你可能感兴趣的:(PHP,PHP,static,static,延迟静态绑定)