您好我在创建一个应该包含我班级所有实例的数组时遇到了一些麻烦。例如,每当我从主类中实例化一个对象时,我自动将该对象放入先前在类中创建的空数组中。
class Meniu_de_baza{
private $nume;
private $descriere_ro;
private $descriere_en;
private $pret;
private $array_obiecte[];
function __construct($n,$d_ro,$d_en,$p){
$this->nume = $n;
$this->descriere_ro = $d_ro;
$this->descriere_en = $d_en;
$this->pret = $p;
$this-array_obiecte = $this-
}
function getPret(){
return $this->pret;
}
function setPret($set_pret){
if(is_numeric($set_pret)){
$this->pret = $set_pret;
}else{
echo "Pretul este invalid!";
}
}
function detalii_mancare(){
echo "Ati comandat {$this->nume} ce contine: <br />" . "{$this->descriere_ro} <br />";
}
function nota_plata(){
echo "Nota Plata: <br />{$this->nume} 1 portie <br /> TOTAL: {$this->pret} RON";
}
}
代码附加为图像,因为我试图将其放入代码块时出现问题。提前致谢。任何建议都表示赞赏。
答案 0 :(得分:1)
小例子
class Sample{
private static $objects=array();
public function __construct()
{
static::$objects[]=$this;
}
public function getObjects(){
return static::$objects;
}
}
声明该字段为静态,因此变量将在类级别而不是在对象级别。
使用方法:
new Sample();
new Sample();
new Sample();
$a=new Sample();
var_dump($a->getObjects());
希望这可以帮到你
为您的代码编辑:
class Meniu_de_baza{
private $nume;
private $descriere_ro;
private $descriere_en;
private $pret;
private static $array_obiecte[];
function __construct($n,$d_ro,$d_en,$p){
$this->nume = $n;
$this->descriere_ro = $d_ro;
$this->descriere_en = $d_en;
$this->pret = $p;
static::$array_obiecte[] = $this;
}
function getPret(){
return $this->pret;
}
function setPret($set_pret){
if(is_numeric($set_pret)){
$this->pret = $set_pret;
}else{
echo "Pretul este invalid!";
}
}
function detalii_mancare(){
echo "Ati comandat {$this->nume} ce contine: <br />" . "{$this->descriere_ro} <br />";
}
function nota_plata(){
echo "Nota Plata: <br />{$this->nume} 1 portie <br /> TOTAL: {$this->pret} RON";
}
您的代码出现问题:
你在static::$array_obiecte = $this;