zoukankan      html  css  js  c++  java
  • 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{
    
    }

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

  • 相关阅读:
    React 使用链表遍历组件树
    React diff 算法
    JavaScript 对象操作
    前端路由hash
    动画运动曲线
    ajax跨域问题
    js版本状态模式
    装饰者模式AOP
    swipe源码循环索引
    组合模式--超级宏命令
  • 原文地址:https://www.cnblogs.com/isuben/p/5534687.html
Copyright © 2011-2022 走看看