【发布时间】:2013-08-23 06:36:34
【问题描述】:
<?php
class MyClass
{
public $prop1 = "I'm a class property!";
public function __construct()
{
echo 'The class "', __CLASS__, '" was initiated!<br />';
}
public function __destruct()
{
echo 'The class "', __CLASS__, '" was destroyed.<br />';
}
public function __toString()
{
echo "Using the toString method: ";
return $this->getProperty();
}
public function setProperty($newval)
{
$this->prop1 = $newval;
}
public function getProperty()
{
return $this->prop1 . "<br />";
}
}
class MyOtherClass extends MyClass
{
public function __construct()
{
parent::__construct(); // Call the parent class's constructor
$this->newSubClass();
}
public function newSubClass()
{
echo "From a new subClass " . __CLASS__ . ".<br />";
}
}
// Create a new object
$newobj = new MyOtherClass;
?>
问题:
如果把$this->newSubClass();改成self::newSubClass();也可以,那么什么时候用$this->newSubClass();,什么时候用self::newSubClass();?
【问题讨论】:
-
self:: 用于静态方法 / $this 用于 obj 本身。
-
和
self几乎从来不是你的意思,通常你想使用static。查看late static binding的信息
标签: php