php中static和self的區別


在閱讀一些框架的源碼時發現了new static(),和new self(),甚是不解,后來查閱資料,才知道static采用了延遲綁定,能准確知道是父類還是子類的調用。這就是說static是個聰明的小孩,家里的親戚的輩分他都能准確的叫出;而不是像他的兄弟self,只知道自己的親爹媽。

例子如下:

<?php

class Father{
    protected  static $name = "father";
    public static function whoami_self(){
        echo self::$name."\n";
    }
    
    public static function whoami_static(){
        echo static::$name."\n";
    }
    
    public static function getInstance_self(){
        return new self();
    }
    
    public static function getInstance_static(){
        return new static();
    }
}

class FatherBrother extends Father{
    protected  static $name = "uncle";
}

FatherBrother::whoami_self(); //father
FatherBrother::whoami_static(); //uncle
var_dump(FatherBrother::getInstance_self()); //father
var_dump(var_dump(FatherBrother::getInstance_static())); //uncle

 

轉載至:https://www.cnblogs.com/xdao/p/static_self_in_php.html


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: