0





95
1

I searched and read about private, public & protected within a class, and I maybe just don't know how to phrase what I'm trying to do.

I am not able to get a class function to use a variable defined as public.

Here's my class:

class Store {  private $wpdb;
  public $store;  public $payroll_total_dollars;
  public $payroll_regular_dollars;
  public $payroll_overtime_dollars;
  public $payroll_vacation_dollars;
  public $payroll_salary_dollars;
  public $payroll_commission_dollars;
  public $payroll_total_percent;
  public $the_last_query;  public function __construct() {
    global $wpdb;
    $this->wpdb = &$wpdb;
    $this->setup_payroll();
  }  public function set_store($store) {
    $this->store = $store;
  }  function setup_payroll() {
      if($this->store != 'all_stores') {
          $this->payroll_regular_dollars = $this->wpdb->get_var( $this->wpdb->prepare ("SELECT sum(regular_hourly) FROM adt_sales WHERE store= '%d'", $this->store));
          $this->the_last_query = $this->wpdb->last_query;
      }
  }
}$store01 = new Store;
$store01->set_store('1');

I'm trying a few things to get the query working in the setup_payroll() function.

If I do this: echo $store01->store, it returns string(1) "1"

If I do this: echo $store01->the_last_query, it returns string(58) "SELECT sum(regular_hourly) FROM adt_sales WHERE store= '0'"

So clearly since the query is receiving 0 where it should actually be 1, the result is NULL.

If I hard-code the number 1 into the query in the setup_payroll() function, it works as expected and returns the value I am looking for within the $payroll_regular_dollars variable, so I don't know where I'm going wrong in trying to get $this->store into that query!

Please help save my sanity!

Question author Drumichael611 | Source

0


1

When you create $store01, the code in your constructor is called. You can't execute code before the constructor; if you want to invoke set_store you need to do it in the constructor so that setup_payroll has that number to reference. (or alternatively you could just invoke setup_payroll() outside of your constructor).

You could change your constructor like so:

public function __construct($v) {    global $wpdb;    $this->set_store($v);    $this->wpdb = &$wpdb;    $this->setup_payroll();}

Then just instantiate it with

$store01 = new Store(1);

This will set_store to whatever you pass into the constructor when a new object is instantiated. With this, setup_payroll should behave a bit more like you expect.

Answer author John-malayny

Ask about this question here!