PHP: Array of objects inside a class
Translation of the original in Catalan. Read it in: CatalàCastellano
After many days with the same error and going round and round on the subject and without a clear solution, today I have managed to make it work...
The problem was that when I made a class that had an attribute made up by an array of objects of another non primitive class, since PHP does not consider variable types, it had problems of type incompatibility and things like that.
Below I attach a very simple example where you can see how the thing works.If someone has some idea to improve the way of storing an array of objects as an attribute inside a class I would be grateful if they let me know. This idea is very useful when making catalogues of products or hierarchical families of objects.
There are few people who use O.O.P. with PHP, since it does not support many of the features of the same but for somewhat big projects it is useful to get into it otherwise it becomes difficult to reuse code on many occasions.
The example is made up of 3 files:
-Clase1.php3 : it is a very simple class, with only two attributes.
-Clase2.php3 : it is the class that has as an attribute an array of objects of the previous class.
-test.php3 : test file, creates an object of Clase2 and adds elements to the array attribute of Clase1.
Codi de la Clase1.php3:
class Clase1 {
var $dada1;
var $dada2;
function Clase1(pdada2="") {
this->dada1=pdada1;
this->dada2=pdada2;
}
function setDada(pdada2="") {
this->dada1=pdada1;
this->dada2=pdada2;
}
function getDada1() {
return $this->dada1;
}
function getDada2() {
return $this->dada2;
}
}
Codi de la Clase2.php3:
class Clase2 {
var $dato;
var $vector;
function Clase2() {
}
function setDato($pdato) {
this->dato=pdato;
}
function addVector(dada2) {
this->vector\["dada1"] = new Clase1(dada2);
}
function getVector($dada1) {
this->vector["$dada1"];
return $a->getDada1();
}
}
Codi de la test.php3:
include("Clase1.php3");
include("Clase2.php3");
$test2 = new Clase2;
$test2->Clase2();
$test2->addVector("test","testejant");
$test2->addVector("test2","testejant2");
$test2->addVector("test3","testejant3");
$test2->addVector("test4","testejant4");
echo $test2->getVector("test");
echo "
n";
echo $test2->getVector("test2");
echo "
n";
echo $test2->getVector("test3");
echo "
n";
echo $test2->getVector("test4");
1 comment
Comments from the old blog, as they were written. Comments are closed.
—
Petit help de programació orientada a objectes en PHP:
"http://www.osnews.com/story.php?news_id=6788">http://www.osnews.com/story...