参考资料:PHP类中self和$this的区别
self:类本身的指针,$this:对象本身的指针
- self即类本身,类本身的静态属性及静态方法是占有内存的,self与$this指向的是不同的内存(即不共享任何属性)本例中 self:: = Demo::
- 以新对象为前提:new self($a) = new static($a) = $this;
代码
<?php
class Demo{public $a=1;public $b;public static $c = 1;public function __construct($a){
$this->a = $a;}public function func(){
echo new self(10) == new static(10);echo "\n";//1echo new self(10) == $this;//1}public function funct(){echo self::$c *= 200;echo "\n";echo Demo::$c *= 200;echo "\n";}
}
$demo = new Demo(10);
$demo->func();echo "\n";//全新对象对比,结果 1
$demo->funct();echo "\n";//self 对静态属性计算 200
$demo->func();echo "\n";//重新对比 结果 1
$demo2 = new Demo(10);
$demo2->funct();echo "\n"; //self 对静态属性计算 40000
结果
E:\server\wwwroot\php_frame_study>php test.php
1
1
200
40000
1
1
8000000
1600000000