__set Sihirli Metodu
Sihirli metot __set, mevcut olmayan veya geçerli bağlamda erişilemeyen bir özelliğe değer atamaya çalışıldığında otomatik olarak çağrılır. Metot iki parametre alır: özelliğin adı ve atanmaya çalışılan değer.
Sözdizimi
public function __set(string $name, mixed $value): void
Örnek
Mevcut olmayan özellikleri ayarlama girişimlerini yakalamak için __set kullanan bir sınıf oluşturalım:
<?php
class User {
private $data = [];
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function getData() {
return $this->data;
}
}
$user = new User();
$user->email = 'test@example.com';
$user->age = 25;
print_r($user->getData());
?>
Kodun çalıştırılmasının sonucu:
Array
(
[email] => test@example.com
[age] => 25
)
Örnek
Verileri ayarlamadan önce doğrulamak için __set kullanımı:
<?php
class Product {
private $price;
public function __set($name, $value) {
if ($name === 'price') {
if (!is_numeric($value) || $value < 0) {
throw new Exception('Geçersiz fiyat değeri');
}
$this->price = $value;
}
}
public function getPrice() {
return $this->price;
}
}
$product = new Product();
$product->price = 100;
echo $product->getPrice();
?>
Kodun çalıştırılmasının sonucu:
100