Utilizei o "método mágico set" em outra aplicação porque assim aprendo melhor. Queria saber se eu posso utilizar o método set dentro do construtor, assim como eu fiz?
<?php
use Alura\School\Student;
require_once 'autoload.php';
$student = new Student('Antonio', 14);
echo $student -> name;
echo $student -> age . PHP_EOL;
echo $student . PHP_EOL;
$student -> age = 1559;
$student-> name = 'Carlos';
echo $student;
<?php
namespace Alura\School;
class Student
{
/**
* class Student
* @package Alura\School
* @property-read float $age
* @property-read string $name
*/
private float $age;
private string $name;
public function __construct(string $name, float $age)
{
$this-> setName($name);
$this-> setAge($age);
}
private function setAge (float $age):void
{
if ($age > 0 && $age < 125) {
$this -> age = $age;
}
else {
echo "Invalid Age!" . PHP_EOL;
exit();
}
}
private function getName ():string
{
return $this -> name;
}
private function getAge ():float
{
return $this -> age;
}
private function setName (string $name)
{
$this -> name = $name;
}
public function __set(string $name, $value)
{
$function = 'set' . ucfirst($name);
return $this->$function($value);
}
public function __get($name)
{
$function = 'get' . ucfirst($name);
return $this->$function();
}
public function __toString()
{
return "name:{$this->name}, age:{$this->age}";
}
}