You could do as follows using encapsulation, where you set all the properties of the class to private or protected (if there is an inheritance relation) and create the methods that were 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 the values in the properties of the class, where this allows you to handle the values before they are assigned to their properties, thus ensuring greater security of integrity of your class data.
Get's : These methods are responsible for allowing properties to be read out of the class, thus enabling you to create only the get's for the properties you want to 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();