const,$this,self static 运用与区别
Code:
class foo{
const TMP = 'This is const TMP';
private static $tmp1 = 0;
private $tmp2 = 1;
function __construct()
{
print self::$tmp1;
//print self::$tmp2; //error $tmp2 is not static
//print $this->tmp1; //null $this->tmp1 is null,tmp1 is static
print $this->tmp2;
print self::TMP; //print 'this is const TMP'
}
static function test()
{
print "this is static fun";
}
}
print foo::TMP; //print const TMP;
foo::test(); //print test() out;
$obj = new foo;
$obj->test(); //this is fun
parent 主要用在扩展class 上,
Code:
<?php
class foo{
const TMP = 'This is const TMP';
private static $tmp1 = 0;
private $tmp2 = 1;
function __construct()
{
print self::$tmp1;
//print self::$tmp2; //error $tmp2 is not static
//print $this->tmp1; //null $this->tmp1 is null,tmp1 is static
print $this->tmp2;
print self::TMP; //print 'this is const TMP'
}
static function test()
{
print "this is static fun";
}
}
class foo2 extends foo{
function __construct()
{
parent::__construct(); //__connstruct used
parent::test(); //print static fun;
print parent::TMP; //print const
//print parent::tmp1; //error
}
}
print foo::TMP; //print const TMP;
foo::test(); //print test() out;
$obj = new foo;
$obj->test(); //this is fun
print "/n Test parent /n";
$obj2 = new foo2();
?>¢
博客主要介绍了PHP中const、$this、self、static的运用与区别,通过代码示例展示了它们在类中的使用情况。同时还讲解了parent在扩展class上的应用,给出了相关代码示例,帮助理解其在继承中的作用。
7711

被折叠的 条评论
为什么被折叠?



