我想模块化函数,但这行不通...
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谢谢你的帮助!
发布于 2013-10-09 05:28:24
你的设计模式很好,只是有一个语法错误。您在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);发布于 2013-10-09 05:29:23
在您的函数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;
}发布于 2013-10-09 05:34:19
echo $r->show_report;在本例中,您试图在不带参数的情况下调用函数。如果这真的是你正在做的,那至少会有一个问题。
取而代之的是,使用参数调用函数:
echo $r->show_report('foo', 1);https://stackoverflow.com/questions/19258734
复制相似问题