0

我想模块化功能,但这不起作用......

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

谢谢您的帮助!

4

4 回答 4

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);
于 2013-10-08T21:28:23.720 回答
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;
}
于 2013-10-08T21:29:23.410 回答
1
echo $r->show_report;

在此示例中,您尝试调用不带参数的函数。如果这确实是您正在做的事情,那至少是一个问题。

相反,使用参数调用函数:

echo $r->show_report('foo', 1);
于 2013-10-08T21:34:18.847 回答
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>

这对静态上下文有用吗?请评论。

于 2013-10-08T21:46:20.733 回答