You could do as follows using encapsulation, where to be set all class properties as private or protected(If there is an inheritance relation) and be create the methods that have become responsible for manipulating these properties, thus ensuring the integrity of the data, which in this case are the set’s and get’s methods, where:
Set’s: These are the methods responsible for assigning values in class properties, where this allows you to process values before they are assigned to your properties, thus ensuring greater security of the integrity of your class’s data.
Get’s: They are the methods responsible for allowing reading properties outside the class, thus enabling you to create only get’s for the properties you want to be read outside the class.
Product class:
<?php
class Produto {
private $nome;
private $categoria;
//Método construtor da classe Produto
public function __construct($nome, Categoria $categoria) {
$this->nome = $nome;
$this->categoria = $categoria;
}
public function setNome($nome) {
$this->nome = $nome;
}
public function getNome() {
return $this->nome;
}
public function setCategoria(Categoria $categoria) {
$this->categoria = $categoria;
}
public function getCategoria() {
return $this->categoria;
}
}
Class Category:
<?php
class Categoria {
private $nome;
//Método construtor da classe Categoria
public function __construct($nome) {
$this->nome = $nome;
}
public function setNome($nome) {
$this->nome = $nome;
}
public function getNome() {
return $this->nome;
}
}
Test file:
<?php
require_once 'Produto.php';
require_once 'Categoria.php';
$categoria = new Categoria('Livro');
$produto = new Produto('Sistema de Banco de Dados', $categoria);
echo 'Produto: ' . $produto->getNome();
echo '<br>';
echo 'Categoria: ' . $produto->getCategoria()->getNome();
You want your object
Produto
receive the objectCategoria
? If yes, you’re right now, just include the class pathCategoria
and treat it normally as an object withinProduto
.– user28595
You in the title say you want to add 2 categories in a product, however did not clarify this in the description, it would be just that?
– marcusagm