我有一个我已经制作的对象
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;
}
}
我使用以下
填充它$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);
}
}
这似乎主要起作用,当我print_r()它我得到了
Array ( [InstanceID] => SalesReportObject Object ( [eventname] => [v_firstname] => [v_secondname] => [soldStock] => Array ( ) ) )
正如您所看到的,它已使用对象的变量名称而不是预期值填充它。 它可能是非常愚蠢的东西,但是我无法看到它(今天已经存在了一段时间)
我的问题是为什么会发生这种情况,我需要修改什么? 提前感谢您的建议
答案 0 :(得分:4)
您需要使用$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;
}
}