我试图通过活动记录模式从sql行创建对象,并在调试时通过print_r显示数组,并且我多次检查了列名以匹配变量名和其他内容,但无济于事。 这是代码要点。
class CustOrder{
public $CustomerId;
public $OrderId;
public $Dish;
public $Dish1;
public $Dish2;
public $Dish3;
public $Dish4;
public $Dish5;
public $Dish6;
public $Dish7;
public $Dish8;
public $Dish9;
public $Dish10;
public $Dish11;
public function __construct($args=[]){
$this->CustomerId = $args['CustomerId'] ?? '';
$this->OrderId = $args['OrderId'] ?? '';
$this->Dish = $args['Dish'] ?? '';
$this->Dish1 = $args['Dish1'] ?? '';
$this->Dish2 = $args['Dish2'] ?? '';
$this->Dish3 = $args['Dish3'] ?? '';
$this->Dish4 = $args['Dish4'] ?? '';
$this->Dish5 = $args['Dish5'] ?? '';
$this->Dish6 = $args['Dish6'] ?? '';
$this->Dish7 = $args['Dish7'] ?? '';
$this->Dish8 = $args['Dish8'] ?? '';
$this->Dish9 = $args['Dis9'] ?? '';
$this->Dish10 = $args['Dish10'] ?? '';
$this->Dish11 = $args['Dish11'] ?? '';
}
static protected $database;
static public function set_database($database){
self::$database = $database;
}
static public function get_all_orders(){
$sql = "Select * from orderz";
return self::find_by_sql($sql);
}
static public function find_by_sql($sql){
$result = self::$database->query($sql);
if(!$result){
exit("database query failed");
}
$object_array=[];
while($record = $result->fetch_assoc()){
$object_array[]=self::instantiate($record);
}
$result->free();
return $object_array;
//return $result;
}
static protected function instantiate($record){
$object = new CustOrder;
//automatic assignment faster and reusable
foreach($record as $property => $value){
if(property_exists($object,$property)){
$object->$property = $value;
echo "hello";
}else{
//echo print_r($record[0]);
}
}
return $object;
}
}
set_database调用是通过PDO进行的,而我正在谈论的方法是实例化的。
答案 0 :(得分:0)
像这样使用它:-
if ('CustomerId' in $object)
或
检查所有内容:-
echo "<pre>";print_r($object);
echo "<pre>";print_r($property);
if(property_exists($object,$property)){
$object->$property = $value;
echo "hello";
}else{
//echo print_r($record[0]);
}