348 of 410 menu

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

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

Example

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

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

'John'

Example

The __get method can be used to implement dynamic properties:

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

Code execution result:

'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
byenru