对象类实例化数组[关闭]
问题描述:
Hello I'm having some trouble creating an array that should hold all the instances of my class. For example I'd like that everytime I instantiate an object from my main class to automatically put that object in an empty array created previously in the class.
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";
}
}
The code is attached as an image due to an issue I've occured trying to put it in a code block. Thanks in advance. Any advice is appreciated.
答
small example
class Sample{
private static $objects=array();
public function __construct()
{
static::$objects[]=$this;
}
public function getObjects(){
return static::$objects;
}
}
declare that field as static so variable will be at class level not at object level.
How to use:
new Sample();
new Sample();
new Sample();
$a=new Sample();
var_dump($a->getObjects());
Hope this might help you
EDIT FOR YOUR CODE:
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";
}
Problem with your code :
you forgot semicolon at static::$array_obiecte = $this;