2012-06-21 64 views
1

鑑於以下類:訪問對象通過一個抽象的功能

<?php 
class test{ 
static public function statfunc() 
    { 
    echo "this is the static function<br/>"; 
      $api= new object; 

    } 
} 

class traductor 
{ 

    public function display() 
    { 
     echo "this is the object function"; 
} 
} 

test::statfunc(); 

$api->display(); 

這不顯示消息"this is the static function<br/>"

有沒有辦法通過靜態函數實例化並將該對象外部?

謝謝......我對對象編程代碼沒有經驗。

回答

2

您應該從靜態函數返回對象:

static public function statfunc() 
{ 
    $api = new traductor; 
    return $api; 
} 

然後返回的對象存儲,您可以使用一個變量。

$api = test::statfunc(); 
$api->display(); 
+0

感謝您的幫助,簡單快捷!感謝編輯也。 –

2

您對聲明的使用有些偏離。您的代碼導致2個致命錯誤。首先,類對象沒有找到,就應該更換:

$api= new object; 

隨着

return new traductor; 

作爲一個靜態類,他們執行一個動作,他們不保存數據,因此static關鍵字。當你開始使用$ this等工具時,請記住這一點。您需要將結果返回給另一個變量。

test::statfunc(); 
$api->display(); 

應該改爲:

$api = test::statfunc(); 
$api->display(); 

見,http://php.net/manual/en/language.oop5.static.php有關靜態關鍵字和例子一些更多的信息。

+0

感謝您的幫助!我會看看你提供的鏈接。 –