Magik metod __set

Magik metod __set, movcud olmayan və ya cari kontekstdə əlçatan olmayan xassəyə dəyər təyin etməyə cəhd edildikdə avtomatik olaraq çağırılır. Metod iki parametr qəbul edir: xassənin adı və təyin edilməyə çalışılan dəyər.

Sintaksis

phppublic function __set(string $name, mixed $value): void

Nümunə

Movcud olmayan xassələrin təyin edilmə cəhdlərini yaxalamaq üçün __set istifadə edən bir sinif yaradaq:

php<?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 icrasının nəticəsi:

phpArray
(
  [email] => test@example.com
  [age] => 25
)

Nümunə

Məlumatları onlar təyin edilməzdən əvvəl yoxlamaq üçün __set istifadəsi:

php<?php
  class Product {
    private $price;
    
    public function __set($name, $value) {
      if ($name === 'price') {
        if (!is_numeric($value) || $value < 0) {
          throw new Exception('Yanlış qiymət dəyəri');
        }
        $this->price = $value;
      }
    }
    
    public function getPrice() {
      return $this->price;
    }
  }
  
  $product = new Product();
  $product->price = 100;
  echo $product->getPrice();
?>

Kodun icrasının nəticəsi:

php100

Həmçinin baxın

  • magik metod __get,
    əlçatan olmayan xassələrin oxunma cəhdlərini yaxalayır
  • magik metod __isset,
    xassələrin mövcudluğunun yoxlanılmasını yaxalayır