天天看点

php类中的$this、static、const、self、final

先看一个例子看输出什么

<?php
    class A{
        const PI = "a_PI";
        static public $m="a_m";
        public $mm = "a_mm";
        private $PI = 'A_PUBLIC_PI';
        protected $GI  =   "A_GI";
        final function F(){
            return "A_F";
        }

        static public function m(){
            echo static::$m,'';
        }
        static public function n(){
            static::n();
        }
        public function get(){
            echo "self::PI = ".self::PI.' | $this->mm = '.$this->mm.' | $this->PI = '.$this->PI .' | static::$m = '.static::$m.' | $this::PI = '.$this::PI.' | $this->GI = '.$this->GI.' | $this->F() = '.$this->F().' | self::F() = '.self::F().' | static::F() = '.static::F();
        }
    }
    class B extends A{
        const PI = "B_PI";
        public $mm = "B_mm";
        static public $m="b_m";
        private $PI = 'B_PUBLIC_PI';
        protected $GI  =   "B_GI";

        static public function m(){
            parent::m();
        }
        static public function n(){
            echo parent::$m,'';
        }
    }
    $bb    =   new B();
    $bb->get();



答案如下
   self::PI = a_PI | $this->mm = B_mm | $this->PI = A_PUBLIC_PI | static::$m = b_m | $this::PI = B_PI | $this->GI = B_GI | $this->F() = A_F | self::F() = A_F | static::F() = A_F
           

结论如下

、父类能调用子类的方法或者属性;

、$this 在父类调用;除了 private 类型,其余都是子类有重写则取子类;没有就选择当前类;

、static 在父类调用;子类有重写则取子类;没有就选择当前类;

、self 当前类有则取当前类;没有则往父类里面找;

、private 的类型 this 调用就是当前类;
           
static
在静态方法内部,不能使用$this(即在静态方法内部只能调用静态成员);

调用静态成员的方法只能是self::方法名、或者parent::方法名、或者类名::方法名

在类的外部,调用静态方法时,可以不用实例化,直接类名::方法名

静态方法执行之后变量的值不会丢失,只会初始化一次,这个值对所有实例都是有效的
           
$this
$this表示当前实例,在类的内部方法访问未声明为const及static的属性时,使用$this->value='phpernote';的形式。
常见用法如:$this->属性,$this->方法
           
const
const PI = ;
调用类的成员是self::PI,而不是self::$PI
           
self
self表示类本身,指向当前的类。通常用来访问类的静态成员、方法和常量
           
final
、如果父类中的方法被声明为 final,则子类无法覆盖该方法

、如果一个类被声明为 final,则不能被继承

、属性不能被定义为 final,只有类和方法才能被定义为 final