Hello good morning and thanks in advance.
I have the following class in php
class Electrodomestico
{
protected $precio_base;
protected $color='blanco';
protected $consumo_energetico;
protected $peso;
}
And I want to check inside the constructor that energy_consumption and that color are correct data. For this I have the following functions
public function comprobarConsumo($letra)
{
if (gettype($letra) == 'string') {
if (
strtoupper($letra) == 'A' ||
strtoupper($letra) == 'B' ||
strtoupper($letra) == 'C' ||
strtoupper($letra) == 'D' ||
strtoupper($letra) == 'E' ||
strtoupper($letra) == 'F'
) {
return $letra;
$this->consumo_energetico = $letra;
} else {
return $letra;
$this->consumo_energetico = 'F';
}
} else {
return $letra;
$this->consumo_energetico = 'F';
}
}
public function comprobarColor($c)
{
if (gettype($c) == 'string') {
if (
strtoupper($c) == 'BLANCO' ||
strtoupper($c) == 'NEGRO' ||
strtoupper($c) == 'ROJO' ||
strtoupper($c) == 'AZUL' ||
strtoupper($c) == 'GRIS'
) {
return $c;
$this->color = $c;
} else {
return $c;
$this->color = 'BLANCO';
}
} else {
return $c;
$this->color = 'BLANCO';
}
}
My problem arises when calling the functions inside the constructor, I have the following syntax, but it returns NULL
function __construct(
$colorElectrodo,
$consumo_energeticoElectrodo,
$pesoElectrodo = 5,
$precio_baseElectrodo = 100
) {
$this->precio_base = $precio_baseElectrodo;
$this->color=$this->comprobarColor($colorElectrodo);
$this->consumo_energetico=$this->comprobarConsumo($consumo_energeticoElectrodo);
$this->peso = $pesoElectrodo;
}
My only idea is to take these methods out of the class, but it is not the most appropriate.
The solution was in the access to the methods and the data they returned, I declared them static and checked the values they returned as follows:
And when using them in the constructor I did it as follows: