The __get Method

The __get method is automatically called when attempting to get the value of a non-existing or inaccessible property of an object. This magic method accepts one parameter - the name of the requested property.

Syntax

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

Example

Let's create a class with the __get method that will return values for non-existing properties:

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;
?>

Code execution result:

php'John'

Example

The __get method can be used to implement dynamic properties:

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

Code execution result:

php'Dynamic value for test'

See Also

  • the __set method,
    which is called when setting a non-existing property
  • the __call method,
    which is called when invoking a non-existing method