Shihab Malayil Shihab Malayil - 1 month ago 11
PHP Question

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

I found so many similar questions here, but i don't understand it because I am newbie in OOP.

I followed this tutorial series to learn OOP.

Here is my code:

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');
}
}
}


please help me to solve this issue. Thanks

Answer

Variable 'this' is just link to object which called method. But you use static modificator. It is mean, this method use in whole class, not in some object. Also it is mean, what not exist object which call this method and evidently, not exist variable 'this'.

At static method you can use variable 'self' only. It link to self class.

And for solving your error, you need remove static modificator.

Comments