2013-10-08 39 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> 

这是做静态上下文?请给出意见。

相关问题