Klasy w php z konstruktorem

Konstruktor pozwala zainicjalizować pola w trakcie tworzenia obiektu.

class Pies{
    private $imie;
    private $rasa;

    function __construct(string $i, string $r){
        $this->imie = $i;
        $this->rasa = $r;
    }
    public function info(){
        echo "$this->imie to pies rasy $this->rasa";
    } 
}

$czarek = new Pies('Czarek', 'owczarek');
$czarek->info();

$pikus = new Pies('Pikuś', 'terrier');
$pikus->info();

Do konstruktora możemy dodać wartości domyślne, które zostaną przypisane jeśli ich nie sprecyzujemy podczas tworzenia nowego obiektu.

class Pies{
    private $imie;
    private $rasa;

    function __construct(string $i = 'Pieseł', string $r = 'kundelek'){
        $this->imie = $i;
        $this->rasa = $r;
    }
    public function info(){
        echo "$this->imie to pies rasy $this->rasa";
    } 
}

$piesio = new Pies();
$piesio->info();
Ask ChatGPT
Set ChatGPT API key
Find your Secret API key in your ChatGPT User settings and paste it here to connect ChatGPT with your Tutor LMS website.
Scroll to Top