PHP passing variables from controller to class error

108 Views Asked by At

I am trying to understand php classes. I'm attempting to make a new class in opencart to centralise some custom queries. In opencart you have models for admin and models for catalog but you cannot use the same model for both...i believe? So i was thinking a new class may do it? My Class:

    class Ship {

    public $product_id = null;

    public function __construct($registry) {
        $this->db = $registry->get('db');
        $this->product_id = $product_id;

    }

    public function getProductDimensions($product_id) {

        $query = $this->db->query("SELECT `length`,`width`,`height`,`length_class_id` FROM " . DB_PREFIX . "product WHERE product_id='" . (int)$product_id . "'");

        return $query->row;

    }


}

And i'm calling the class function like this:

$product_size = $this->ship->getProductDimensions('872');

I get an error: Fatal error: Uncaught Error: Call to a member function getProductDimensions() on null

I used the cart class as a guide and $this->cart->add(variables) works from catalog/controllers , but because i dont fully understand classes, i must be missing something.

Can anyone help me to understand(now thats a question), what i am missing?

2

There are 2 best solutions below

0
Steve On

Ok, after some hours, i found the answer.

I needed to load the class, i thought they loaded automatically at startup?

$this->load->library('ship');

$product_size = $this->ship->getProductDimensions('872');

Hey ho, now i can carry on adding stuff.

1
IMSoP On

It's worth getting clear in your head what functionality is part of PHP, and what is part of OpenCart.

In PHP, $this->ship just means "a property called $ship on the current object", and has no automatic relationship to the class Ship. Somewhere in OpenCart there needs to be some code that assigns an instance of your Ship class to an appropriate property

A really simple example would look like this:

class OpenCartBaseClass {
    protected $ship;

    public function __construct() {
        $this->ship = new Ship;
    }
}

class YourCustomCode extends OpenCartBaseClass {
    public function doSomething() {
        $this->ship->getProductDimensions('872');
    }
}

So the documentation you need to find is how to tell OpenCart to create an instance of your class, and assign it to a property of the same name.