PHP OOP - Oluşturucu
PHP - __construct İşlevi
Yapıcı, nesnenin oluşturulmasından sonra bir nesnenin özelliklerini başlatmanıza izin verir.
Bir __construct()
fonksiyon yaratırsanız, bir sınıftan bir nesne oluşturduğunuzda PHP otomatik olarak bu fonksiyonu çağırır.
Yapı fonksiyonunun iki alt çizgi (__) ile başladığına dikkat edin!
Aşağıdaki örnekte, bir kurucu kullanmanın bizi kod miktarını azaltan set_name() yöntemini çağırmaktan kurtardığını görüyoruz:
Örnek
<?php
class Fruit {
public
$name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
Başka bir örnek:
Örnek
<?php
class Fruit {
public
$name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo
"<br>";
echo $apple->get_color();
?>