編輯問題以更好地反映我的需求。調用父類方法
看看下面的例子:
class Base
{
public $Text = null;
public function __construct()
{
$this->Text = new Base_Text();
}
}
class Base_Text extends Base
{
public $Is = null;
public function __construct()
{
$this->Is = new Base_Text_Is();
}
public function CammelCase($string)
{
return trim(str_replace(' ', '', ucwords($string)));
}
}
class Base_Text_Is extends Base_Text
{
public function CammelCase($string)
{
return ($string === $this->CammelCase($string)); // doesn't work
}
}
我怎樣才能修復Base_Text_Is::CammelCase()
方法,無需調用Base_Text類靜態(不使用parent::
或Base_Text::
)?
我想出了這樣的情況下,唯一的解決方案是創建一個單獨的功能是這樣的:
function Base()
{
static $instance = null;
if (is_null($instance) === true)
{
$instance = new Base();
}
return $instance;
}
並更改Base_Text_Is::CammelCase()
方法是:
return ($string === Base()->Text->CammelCase($string));
而且爲了以避免創建Base類的兩個對象實例,而不是:
$base = new Base();
$base->Text->Is->CammelCase('MethodOverloading'); // true
我只是做:
Base()->Text->Is->CammelCase('MethodOverloading'); // true
這是一個好的做法呢?還有其他解決方案嗎?
我不在Darrell的回答中得到你最後的評論。你無法訪問'Base_Text'的非靜態屬性?你想從哪裏打電話給他們?我想你應該進一步解釋這一點。 – 2010-01-09 22:24:27
@Felix:我試圖儘可能簡化示例,有些情況下我無法靜態調用父方法,因爲它依賴於實例化的屬性。 – 2010-01-09 22:36:05