hyclrs hyclrs - 7 months ago 10
PHP Question

Associative array containing objects, each containing an array, filling with variable names instead of the values

I have an object I've made

class SalesReportObject
{
public $eventname = "";
public $v_firstname = "";
public $v_secondname = "";
public $soldStock = array();
function Push($productname, $soldquantity)
{
$soldStock[$productname] = $soldquantity;
}
function Sum($productname, $soldquantity)
{
$soldStock[$productname] += $soldquantity;
}
function __construct($e, $f, $s)
{
$eventname = $e;
$v_firstname = $f;
$v_secondname = $s;
}

}


And I'm populating it using the following

$salesreportq = 'SELECT Volunteers.SecondName, Volunteers.FirstName, Events.EventName, ItemIssue.Quantity, ItemIssue.ReturnQuantity, Stock.ProductName, EventInstance.InstanceID
FROM EventInstance
INNER JOIN Events ON EventInstance.EventID = Events.EventID
INNER JOIN ItemIssue ON EventInstance.InstanceID = ItemIssue.InstanceID
INNER JOIN Volunteers ON EventInstance.VolunteerID = Volunteers.VolunteerID
INNER JOIN Stock ON ItemIssue.StockID = Stock.StockID
WHERE (ItemIssue.Returned = ?)';
$yes = array('Yes');
$salesreportres = sqlsrv_query($conn, $salesreportq, $yes);
$arr = array();

while ($sRow = sqlsrv_fetch_array($salesreportres, SQLSRV_FETCH_ASSOC))
{
$sold = $sRow['Quantity'] - $sRow['ReturnQuantity'];

if (array_key_exists($sRow['InstanceID'], $arr))
{

if (array_key_exists($arr[$sRow['InstanceID']]->$soldStock['ProductName']))
{
$arr['InstanceID']->Sum($sRow['InstanceID'], $sold);
}
else
{
$arr['InstanceID']->Push($sRow['InstanceID'], $sold);
}
}
else
{
$arr['InstanceID'] = new SalesReportObject($sRow['EventName'], $sRow['FirstName'], $sRow['SecondName']);
$arr['InstanceID']->Push($sRow['InstanceID'], $sold);
}

}


Which seems to mostly work, when I print_r() it I get

Array ( [InstanceID] => SalesReportObject Object ( [eventname] => [v_firstname] => [v_secondname] => [soldStock] => Array ( ) ) )


As you can see it has filled it with variable names of the object instead of the intended values.
It's probably something really dumb, but I can't see it (been at this for a while today)

My question is why is this happening and what do I need to amend?
Thanks in advance for your advice

Answer

You need to reference your class properties with $this. Replace your class code with this:

class SalesReportObject
{
    public $eventname = "";
    public $v_firstname = "";
    public $v_secondname = "";
    public $soldStock = array();

    function Push($productname, $soldquantity)
    {
        $this->soldStock[$productname] = $soldquantity;

    }

    function Sum($productname, $soldquantity)
    {
        $this->soldStock[$productname] += $soldquantity;
    }

    function __construct($e, $f, $s)
    {
        $this->eventname = $e;
        $this->v_firstname = $f;
        $this->v_secondname = $s;
    }
}
Comments