PHP面向对象编程
时间:2006-12-21 来源:njuguo
php5 相比 php4 而言有了很多面向对象的特性,今天偶然写了几个测试实例,发现一些很微妙的事情。
1.对象生存周期
class Name
{
private $name;
function __construct($name)
{
$this->name = $name;
}
function __destruct()
{
echo 'destruct '.$this->name.'
';
}
function printName()
{
echo $this->name.'
';
}
}
$obj1 = new Name('liuhong');
$obj1->printName();
$obj2 = new Name('long');
$obj2->printName();
?>
程序输出结果是:
liuhong
long
destruct liuhong
destruct long
由此可以猜想,PHP 中的对象生存周期是整个页面,为了证实这个想法,用下面的程序测试:
class Name
{
private $name;
function __construct($name)
{
$this->name = $name;
}
function __destruct()
{
echo 'destruct '.$this->name.'
';
}
function printName()
{
echo $this->name.'
';
}
}
$obj1 = new Name('liuhong');
$obj1->printName();
$obj1->__destruct();
$obj1->printName();
$obj2 = new Name('long');
$obj2->printName();
?>
输出结果是:
liuhong
destruct liuhong
liuhong
long
destruct liuhong
destruct long
可见 PHP 的对象生存周期确实是整个页面。
2.this, self, 类名
一段程序,猜测一下输出结果:
class Counter
{
private $cnt = 0;
function printCount()
{
if(isset($this->cnt))
{
echo 'this
';
}
if(isset(self::$cnt))
{
echo 'self
';
}
if(isset(Counter::$cnt))
{
echo 'Counter
';
}
}
}
$obj = new Counter();
$obj->printCount();
?>
结果是:
this
再看下面的程序:
class Counter
{
private static $cnt = 0;
function printCount()
{
if(isset($this->cnt))
{
echo 'this
';
}
if(isset(self::$cnt))
{
echo 'self
';
}
if(isset(Counter::$cnt))
{
echo 'Counter
';
}
}
}
$obj = new Counter();
$obj->printCount();
?>
输出结果是:
self
Counter
有意上两个程序可以得知:this 只能引用非 static 类型的成员,而 self 和类名只能引用 static 类型的成员。
相关阅读 更多 +
排行榜 更多 +