php static 和self区别

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

<?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{

}

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

posted @ 2016-05-27 15:05  雨落知音  阅读(346)  评论(0编辑  收藏  举报