我想模块化函数,但这不起作用...
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
感谢您的帮助!
你的设计模式很好,你只是有一个语法错误。 您在 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);
在函数内部,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;
}
echo $r->show_report;
在此示例中,您尝试调用不带参数的函数。如果这真的是你正在做的事情,那至少是一个问题。
相反,使用参数调用函数:
echo $r->show_report('foo', 1);
谢谢大家。多亏了 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>
这是对静态上下文的处理吗?请评论。