实际上从数据库中获取数据后,我想创建一个新的Object并将此对象插入到数组中但是当我检查数组时它显示的是NULL值 这是我的代码:
<?php
$query = "sql query";
$filter_Result = mysqli_query($con, $query);
$newOrders = Array();
while ($row = mysqli_fetch_array($filter_Result)) {
$order;
$orderId = $row['order_id']; //fetch row id
$temp = check_id($newOrders, $orderId);
if ($temp != null) {
$order = $temp;
} else {
echo " <br>";
$order = new Order($row['order_id'], $row['status'], $row['created_Date']);
$newOrders[] = $order;
}
$item = new Item($row['status'], $row['quantity']);
$order->AddItem($item, null);
}
function check_id($newOrders, $orderId) {
$length = count($newOrders);
for ($i = 0; $i < $length; $i++) {
if ($newOrders[$i]->$orderId == $orderId)
return $newOrders[$i];
}
return null;
}
foreach ($newOrders as $order) {
}
?>
答案 0 :(得分:1)
您的Order类中有一个变量
var $order_Id;
但是你尝试将值分配给$ orderId,它不存在
$this->orderId = $orderId;
我建议在开发时打开所有PHP错误。你可以在你的PHP代码中包含这个,看看你是否有任何错误。用肉眼很难看到所有小错误:)让PHP为你做。
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
有关错误报告的更多信息here。
答案 1 :(得分:0)
你有几个小错误,例如错误地使用“this”,使用“orderId”的不同名称,加上构造函数的错误名称。构造函数名称应为“Order”或“__construct”,“Item”构造函数的名称相同。
class Order {
/* Member variables */
var $orderId;
var $status;
var $createdDate;
var $items = array();
function Order($orderId, $status, $createdDate)
{
$this->orderId = $orderId;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
$c = new Order(1, 'OK', 'today');
print_r($c);
答案 2 :(得分:0)
现在我在PHP中找到了解决方案,我们必须使用 __ construct()来创建一个构造函数.... 因此,请使用 __ construct 而不是类名来访问更多信息: __construct() vs SameAsClassName() for constructor in PHP
答案 3 :(得分:-2)
new_order.php
<?php
class Order {
/* Member variables */
var $order_Id;
var $status;
var $createdDate;
var $items = array();
function __Order($order_Id, $status, $createdDate)
{
$this->order_Id = $order_Id;
$this->status = $status;
$this->createdDate = $createdDate;
}
function AddItem($itemId,$quantity)
{
$item = new Item($itemId,$quantity);
$items[] = $item;
}
}
class Item {
var $productId;
var $productName;
var $quantity;
var $personalization;
function __Item($productId, $quantity)
{
$this->productId = $productId;
$this->productName = $productName;
$this->quantity = $quantity;
$this->personalization = $personalization;
}
}
?>