【发布时间】:2015-01-10 17:29:55
【问题描述】:
StackOverflow,这里的第一个问题。我正在尝试使用 MySQL 学习 PHP,但我遇到了数组和对象的问题。
这就是我想要发生的事情。
Category object {
[details] => Array (
[category] => Desktop
[notes] => Lorem ipsum dolor sit amet, consectetur adipisicing elit.
)
[properties] => Array (
[0] => Property Object (
[details] => Array (
[property] => Hard Disk Size
[category] => Desktop
[notes] =>
)
)
[1] => Property Object (
[details] => Array (
[property] => Memory Frequency
[category] => Desktop
[notes] =>
)
)
[2] => Property Object (
[details] => Array (
[property] => Video Card Graphics Adapter
[category] => Desktop
[notes] =>
)
)
)
但结果是 [properties] 数组下的所有对象都具有相同的值。 (properties[2] 的值变成了 properties[0] 和 properties[1] 的值。)
我修改了代码以将每个对象的 details->property 值推送到数组中,它可以正常工作。只有在推动物体时我才有问题。
这是代码。
class Category {
public static final function generate_template() {
return array(
"category" => null,
"notes" => null
);
}
private static function query_category( $input_string ) {
global $connection;
$stmt = $connection->prepare(
"SELECT * FROM categories WHERE category = ? LIMIT 1"
);
$stmt->bind_param( "s", $input_string );
if ( !$stmt->execute() ) return false;
$category_details = Category::generate_template();
$stmt->bind_result(
$category_details["category"],
$category_details["notes"]
);
$stmt->fetch();
return $category_details;
}
private static function query_category_properties( $category ) {
global $connection;
$stmt = $connection->prepare(
"SELECT * FROM properties WHERE category = ?"
);
$stmt->bind_param( "s", $category );
if ( !$stmt->execute() ) return false;
$property_details = Property::generate_template();
$stmt->bind_result(
$property_details["property"],
$property_details["category"],
$property_details["notes"]
);
$properties_array;
while ( $stmt->fetch() ) {
$properties_array[] = new Property( $property_details );
// This caused the problem.
// It works as expected when written like this.
// $properties_array[] = (new Property( $property_details ))->details["property"];
}
return $properties_array;
}
// Object Things
public $details;
public $properties = null;
public function __construct( $category ) {
$this->details = Category::query_category( $category );
$this->properties = Category::query_category_properties( $category );
}
}
class Property {
public static final function generate_template() {
return array(
"property" => null,
"category" => null,
"notes" => null
);
}
public $details = array();
public function __construct( $property_details ) {
$this->details = $property_details;
}
}
$category = new Category( "Desktop" );
print_r( $category );
?>
这就是存储代码属性的作用。 https://lh5.googleusercontent.com/xe5N2U6rGOlr3x4vh_Qm0CFRS8-7pDryn9FuSldyPXN5huRhBy31bqH1d7H4AS8phDcfunyp9OE=w1332-h521
(我的声誉还不足以发布图片。我只是从这里开始。)
我想做的是将这些对象存储在一个数组中,但它似乎不起作用。
感谢阅读。
【问题讨论】:
-
你能把代码贴出来吗?
-
请在这里发布相关代码
-
将代码添加到主体中。