Make like a array Associative is really a solution, even because an object does not cease to be one. I agree it’s a beautiful gambit and should be avoided unless it really makes sense.
So just create the object in the traditional way. First creates an auxiliary object, then initializes each property, and the one that will have an object will use this auxiliary object. The basics are like this, there’s no way.
Another technique is to create a constructor in the class to facilitate the creation of the object. As the default PHP constructor is very limited and would create other problems in the code I prefer (although this would not be ideal in another language) to create static functions that work as constructors, thus frees the constructor without parameters and allows a kind of overloading of builders.
So I created a constructor that takes all the necessary arguments to fill all the properties, including the one that is an object that will be created in this "constructor".
I created another constructor that takes only the arguments to fill the properties and requires your code to create an instance of the property that is an object. In this case, to facilitate also created a "constructor" to create this object.
In another language this could be done more smoothly.
I don’t know if this is the best way because I don’t do OOP in PHP, but it’s the most obvious to me.
class ObjetoSimples {
var $nome;
var $cargo;
var $turno;
public static function construtor($nome, $cargo, $turno) {
$obj = new ObjetoSimples();
$obj->nome = $nome;
$obj->cargo = $cargo;
$obj->turno = $turno;
return $obj;
}
}
class ObjetoComposto {
public static function construtor($nome, $setor, $nome2, $cargo, $turno) {
$obj = new ObjetoComposto();
$obj->nome = $nome;
$obj->setor = $setor;
$obj->equipe = new ObjetoSimples();
$obj->equipe->nome = $nome2;
$obj->equipe->cargo = $cargo;
$obj->equipe->turno = $turno;
return $obj;
}
public static function construtor2($nome, $setor, $obj2) {
$obj = new ObjetoComposto();
$obj->nome = $nome;
$obj->setor = $setor;
$obj->equipe = $obj2;
return $obj;
}
var $nome;
var $setor;
var $equipe;
}
$obj = new ObjetoSimples();
$obj->nome = "joao";
$obj->cargo = "gerente";
$obj->turno = "noite";
$obj2 = new ObjetoComposto();
$obj2->nome = "maria";
$obj2->setor = "fabrica";
$obj2->equipe = $obj;
$obj3 = ObjetoComposto::construtor("maria", "fabrica", "joao", "gerente", "noite");
$obj4 = ObjetoComposto::construtor2("maria", "fabrica", ObjetoSimples::construtor("joao", "gerente", "noite"));
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I have seen with the use of arrays, but I want to avoid multidimensional matrices, and as I am inciting in object orientation, I saw myself in this complex of levels and sublevels of variables. It would be possible to update the team through Objetocomposto without interfering with your sector and your name?
– Cleberson