Solucionado (ver solução)
Solucionado
(ver solução)
2
respostas

Exercício_set

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}";
    }

}
2 respostas
solução!

Olá!

Teria que testar, mas na teoria pode sim!

Eu executei o código e não houve problemas hehe, mas não sei se essa é uma maneira correta de proceder segundo os bons modos de programação.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software