2013-10-08 106 views
0

我想模塊化的功能,但是這是行不通的短PHP函數...如何編寫共同努力

class Review { 
    public function show_report($db, $id){ 
     // Query the DB on $id 
     $x = $this->get_survey($db, 1); 
     $y = $this->get_survey($db, 2); 
     // Use x and y to build a report 
     return $a_report; 
    } 
    private function get_survey($db, $n){ 
     // Query the DB for a certain survey number 
     if($n == 1){ 
      // Perform some logic 
     } else { 
      // Perform some other logic 
     } 
     return $a_survey; 
    } 
}; 

使用這樣的類..

<?php 
    include_once('api/Review.class.php'); 
    $r = new Review(); 
?> 
<p> 
<?php 
    echo Review::show_report($db, $id); 
?> 
</p> 

PHP拋出這個:

Fatal error: Using $this when not in object context in Review.class.php 

感謝您的幫助!

回答

1

你的設計模式很好,你只是有一個語法錯誤。你已經錯過了show_report()在你的方法$符號調用,它應該是這樣的:

public function show_report($db, $id){ 
    // Query the DB on $id 
    $x = $this->get_survey($db, 1); 
    $y = $this->get_survey($db, 2); 
    // Use x and y to build a report 
    return $a_report; 
} 

此外,在課程結束時,分號是不必要的。

最後,正如其他人所說,你需要調用show_report與參數,像這樣:

echo $r->show_report($db, $id); 
+0

現在我得到了'致命錯誤:當不在42行的Review.class.php中的對象上下文中時使用$ this' – broinjc

+1

您能否發佈完整的代碼,因爲在示例代碼中沒有聲明變量? – David

+0

我試圖抽象出一些細節(這是一個很長的文件),這樣做的準確性我就搞砸了。我的錯。好建議! – broinjc

1

裏面你的函數show_report($db, $id)this指針沒有前綴$標誌這將導致語法錯誤。另外在第二部分中,該函數不用參數調用。 該函數有像她那樣:

public function show_report($db, $id){ 
    // Query the DB on $id 
    $x = $this->get_survey($db, 1); 
    $y = $this->get_survey($db, 2); 
    // Use x and y to build a report 
    return $a_report; 
} 
+0

這是我的問題之一。 – broinjc

1
echo $r->show_report; 

在這個例子中,你正試圖調用該函數不帶參數。如果這真的是你在做什麼,那至少會有一個問題。

相反,調用帶參數的功能:

echo $r->show_report('foo', 1); 
+0

這恰好在根本原因旁邊。我在靜態上下文中調用show_report。 – broinjc

+1

啊,你沒有'回聲評論:: show_report($ db,$ id);'在你原來的帖子中,或者我會提到的是,你需要做'echo $ r-> show_report( $ db,$ id);'而是 – andmatand

0

謝謝大家。我修復了所有的語法錯誤,感謝https://stackoverflow.com/a/19258788/1004107。這是問題的根源我相信:

<?php 
    include_once('api/Review.class.php'); 
    $r = new Review(); 
?> 
<p> 
<?php 
    echo Review::show_report($db, $id); 
?> 
</p> 

應該是...

<?php 
    include_once('api/Review.class.php'); 
    $r = new Review(); 
?> 
<p> 
<?php 
    echo $r->show_report($db, $id); 
?> 
</p> 

這是做靜態上下文?請給出意見。

相關問題