Metode __get

Metode __get secara otomatis dipanggil ketika ada upaya untuk mengambil nilai properti objek yang tidak ada atau tidak dapat diakses. Metode ajaib ini menerima satu parameter - nama properti yang diminta.

Sintaks

phppublic function __get(string $name) {
  // implementasi
}

Contoh

Mari buat kelas dengan metode __get, yang akan mengembalikan nilai untuk properti yang tidak ada:

php<?php
  class User {
    private $data = [
      'name' => 'John',
      'age' => 30
    ];
    
    public function __get($name) {
      if (array_key_exists($name, $this->data)) {
        return $this->data[$name];
      }
      return null;
    }
  }
  
  $user = new User();
  echo $user->name;
?>

Hasil eksekusi kode:

php'John'

Contoh

Metode __get dapat digunakan untuk mengimplementasikan properti dinamis:

php<?php
  class DynamicProperties {
    public function __get($name) {
      return "Nilai dinamis untuk {$name}";
    }
  }
  
  $obj = new DynamicProperties();
  echo $obj->test;
?>

Hasil eksekusi kode:

php'Nilai dinamis untuk test'

Lihat juga

  • metode __set,
    yang dipanggil saat mengatur properti yang tidak ada
  • metode __call,
    yang dipanggil saat memanggil metode yang tidak ada