2011-06-16 112 views
0

這是我的第一個問題PHP致命錯誤:調用一個成員函數getScore()一個非對象在

我有以下類

class ProDetection { 
public function ProDetection () { } 
public function detect($word) { 
    ............ 
} 
public function getScore() { 
    return $score; 
} 
} 

class SaveDetection { 
public function SaveDetection($words) { 
    $proDetection = new ProDetection(); 
    for($i=0;$i<sizeof($words);$i++) { 
     $proDetection->detect($words[$i]); 
    } 
} 
public function getScore() { 
    return $this->proDetection->getScore();\\line 22 
} 
} 

在其他PHP文件,我是嘗試調用SaveDetection getScore();

$konten = "xxxx xxxx xxx"; 
$save = new SaveDetection($konten); 
print_r($save->getScore()); 

但我得到了一個錯誤信息

公告:未定義的屬性:SaveDetection :: $ proDetection在C:\ XAMPP \ htdocs中\ inovasi \上線SaveDetection.php 22

致命錯誤:調用一個成員函數getScore(c)中的非對象上:\ XAMPP \ htdocs中\ inovasi \上線SaveDetection.php 22

請需要您的幫助

回答

0

試試這個。聲明變量爲private(表兄弟姐妹,如果你的代碼的增長,這是很難找到什麼都對象或變量在課堂上使用。)

class SaveDetection { 
    private $proDetection = null; 
    public function __construct($words) { 
     $this->proDetection = new ProDetection(); 
     for($i=0;$i<sizeof($words);$i++) { 
      $this->proDetection->detect($words[$i]); 
     } 
    } 
    public function getScore() { 
     return $this->proDetection->getScore();\\line 22 
    } 

    private $proDetection; 

} 
+0

Hi Sahal,非常感謝。是工作 – Ahmad 2011-06-16 05:02:26

2

你永遠不聲明成員變量$proDetection。基本上你SaveDetection構造您聲明$proDetection作爲一個局部變量

class SaveDetection { 

    public function SaveDetection($words) { 
     $this->proDetection = new ProDetection(); 
     for($i=0;$i<sizeof($words);$i++) { 
      $this->proDetection->detect($words[$i]); 
     } 
    } 
    public function getScore() { 
     return $this->proDetection->getScore();\\line 22 
    } 

    private $proDetection; 

} 

編輯:

PS。你應該真的使用PHP的__construct()語法來代替舊式的構造函數。見here

class SaveDetection { 

    public function __construct($words) { 
     $this->proDetection = new ProDetection(); 
     for($i=0;$i<sizeof($words);$i++) { 
      $this->proDetection->detect($words[$i]); 
     } 
    } 
+0

嗨GWW」太感謝了,它的工作! – Ahmad 2011-06-16 04:53:16

+0

太棒了。感謝您的快速回復 – Ahmad 2011-06-16 05:03:09

相關問題