致命错误:在第10行开销.php的对象上下文中没有使用$this


Fatal error: Using $this when not in object context in Expense.php on line 10

我在这里发现了很多类似的问题,但我不明白,因为我是OOP的新手。

我遵循这个教程系列来学习OOP。

下面是我的代码:
include_once 'core/init.php';
if(Session::exists('home')){
    echo Session::flash('home');
}
$user = new User();
if($user->isLoggedIn()){
} else {
    Redirect::to('index.php');
}
if(Input::exist()){
    $validate = new Validate();
    $validation = $validate->check($_POST, array(
        'date' => array('required' => true),
        'vendor' => array('required' => true),
        'invoice-no' => array('required' => true),
        'terms-or-payment-account' => array('required' => true),
        'type-of-expense-1' => array('required' => true),
        'description-1' => array('required' => true),
        'quantity-1' => array('required' => true),
        'price-1' => array('required' => true),
        'amount-1' => array('required' => true)
    ));
    if($validation->passed()){
        $expense = new Expense();
        try{
            $expense->record(array(
                'date' => Input::get('date'),
                'vendor' => Input::get('vendor'),
                'invoice-no' => Input::get('invoice-no'),
                'terms-or-payment-account' => Input::get('terms-or-payment-account'),
                'type-of-expense' => Input::get('type-of-expense-1'),
                'description' => Input::get('description-1'), 
                'quantity' => Input::get('quantity-1'),
                'price' => Input::get('price-1'),
                'amount' => Input::get('amount-1')
            ));
        } catch(Exception $e){
            die($e->getMessage());
        }
        if($expense->record()){
            echo 'success';
        }
    } else {
         //output errors
        foreach ($validation->errors() as $error) {
            echo $error, '<br/>';
        }
    }
}

Expense.php:

class Expense{
    private $_db;
    public function __construct($expense = NULL){
        $this->_db = DB::getInstance();
    }
    public static function record($fields){
        if(!$this->_db->insert('expenses', $fields)){
            throw new Exception('There is a problem recording expense');
        }
    }
}

请帮我解决这个问题由于

Expense#record函数为静态。这意味着对象尚未实例化,但类已实例化。$this是指向实例化对象的指针。因为在这个方法的作用域中没有实例化的对象,所以$this总是返回null。你看到的错误是PHP告诉你这个的方式。

使此工作的最简单方法是从Expense#record方法签名中删除static。这将使该方法成为费用对象的方法,而不是像现在这样成为费用类的方法。因为你已经在$validation->passed()之后实例化了一个费用对象,这应该不是问题。->record()方法将按预期工作。

如果你绝对想保持记录方法为static,那么你必须改变方法在静态上下文中工作;像下面的

class Expense{
    private static $_db = DB::getInstance();
    public static function record($fields){
        if(!self->_db->insert('expenses', $fields)){
            throw new Exception('There is a problem recording expense');
        }
    }
}

变量'这个'只是链接到调用方法的对象。但是你使用静态修饰符。这意味着,这个方法在整个类中使用,而不是在某个对象中使用。也就是说,调用这个方法的不存在的对象和显然不存在的变量'this'

在静态方法中,只能使用变量'self'。它链接到self类

为了解决你的错误,你需要删除静态修饰符