我创建了一个包含三个属性的Magazine类,我希望在创建对象时将其直接存储到数组中。现在,我认为我能做的只是直接在数组中创建新对象,但它似乎不起作用?
<?php
class Magazine {
public $id;
public $name;
public $price;
public function __contruct($id, $name, $price) {
$this->id = $id;
$this->name = $name;
$this->price = $price;
}
}
$magazines = array(
new Magazine("svg_aftbld","Stavanger Aftenblad", 200),
new Magazine("tsk_ubld","Teknisk Ukeblad", 300),
new Magazine("se_ho","Se og Hør", 100),
new Magazine("fam","Familien", 150)
);
print_r($magazines);
?>
这是以上代码的输出:
Array ( [0] => Magazine Object ( [id] => [name] => [price] => ) [1] => Magazine Object ( [id] => [name] => [price] => ) [2] => Magazine Object ( [id] => [name] => [price] => ) [3] => Magazine Object ( [id] => [name] => [price] => ) )
我还尝试创建一个空数组,然后通过推送新对象来填充它:
<?php
array_push($magazines,new Magazine("svg_aftbld","Stavanger Aftenblad", 200));
array_push($magazines,new Magazine("tsk_ubld","Teknisk Ukeblad", 300));
array_push($magazines,new Magazine("se_ho","Se og Hør", 100));
array_push($magazines,new Magazine("fam","Familien", 150));
?>
但它产生的输出与以前相同。
正如您可能猜到的那样,我正在学习PHP,而且我来自Java。我已经阅读了几个类似的问题,但是大多数问题似乎都过于复杂。但我想可能是不太了解PHP的人。随意教我最佳实践;)
答案 0 :(得分:5)
你写了__contruct
而不是__construct
...