Why am I not able to use $this is an opencart helper?
I have the following helper function in system/helper/wholesaler.php:
<?php function is_wholesaler() { return $this->customer->getCustomerGroupId() != 1 ? TRUE : FALSE; } ?>
I loaded the helper in system/startup.php
The problem is that when I try to use the function I get a fatal error "Fatal error: Using $this when not in object context". Is there a way to use $this in a helper?
One alternative option would be to send $this as an argument in is_wholesaler() or add the function in library/customer.php and call it with $this->customer->is_wholesaler() in my opencart template view files.
Answers
Try to create an object for the Customer and you can use that object as an reference for that class
$h = new Customer(); function is_wholesaler() { return $h->getCustomerGroupId() != 1 ? TRUE : FALSE; }
Or you can also create reference like
return Customer::getCustomerGroupId() != 1 ? TRUE : FALSE;
$this refers to an object (class) instance, you can't use it in a individual, you can put function is_wholesaler into a class like:
class Helper{ private $customer; public function __construct($customer){ $this->customer = $customer; } function is_wholesaler() { return $this->customer->getCustomerGroupId() != 1 ? TRUE : FALSE; } } $customer = new Customer(); //I suppose you have a class named Customer in library/customer.php $helper = new Helper($customer); $is_wholesaler = $heler->is_wholesaler();
or, you just modify the function is_wholesaler it self as following:
function is_wholesaler() { $customer = new Customer(); //still suppose you have a class named Customer return $customer->getCustomerGroupId() != 1 ? TRUE : FALSE; }