__get, __set, __isset, __unset
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 46 of 91.
PHP provides four magic methods that intercept property access: __get(), __set(), __isset(), and __unset(). These are triggered when you try to access properties that don't exist or are inaccessible.
The __get() method is called when reading an inaccessible property, while __set() handles writing to one. This lets you create dynamic properties or add logic when properties are accessed:
<?php
class DynamicObject {
private array $data = [];
public function __get(string $name): mixed {
return $this->data[$name] ?? null;
}
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
}
$obj = new DynamicObject();
$obj->title = "Hello";
$obj->count = 42;
echo $obj->title . " - " . $obj->count;
Output:
Hello - 42The __isset() method is triggered by isset() or empty(), and __unset() responds to the unset() function:
<?php
class DynamicObject {
private array $data = [];
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
public function __isset(string $name): bool {
return isset($this->data[$name]);
}
public function __unset(string $name): void {
unset($this->data[$name]);
}
}
$obj = new DynamicObject();
$obj->name = "Test";
echo isset($obj->name) ? "exists" : "missing";
Output:
existsThese methods are commonly used to create flexible data containers, implement lazy loading, or build objects that behave like arrays while maintaining object-oriented structure.
Challenge
EasyLet's build a flexible configuration manager that stores settings dynamically using magic methods. Your class will intercept property access to manage configuration values, check if settings exist, and remove them when needed — all without explicitly defining each property.
You'll organize your code across two files:
Config.php— Create aConfigclass that uses a private array to store configuration values internally. Implement all four property magic methods:__get($name)— Returns the value for the given key, or"undefined"if the key doesn't exist__set($name, $value)— Stores the value under the given key__isset($name)— Returns whether the key exists in the configuration__unset($name)— Removes the key from the configuration
count()that returns the number of stored settings.main.php— Include the Config file. You'll receive three inputs: a setting name, a setting value, and a second setting name. Create aConfiginstance and perform these operations:- Set the first setting to the given value
- Print whether the first setting exists using
isset()— output"exists"or"missing" - Print the value of the first setting
- Print the current count of settings
- Use
unset()to remove the first setting - Print whether the first setting exists now — output
"exists"or"missing" - Print the value of the second setting (which was never set)
Each output should be on its own line. The magic methods let you interact with your Config object using natural property syntax like $config->theme = "dark" and isset($config->theme), even though no actual properties are defined.
Cheat sheet
PHP provides four magic methods to intercept property access:
__get(string $name): mixed— Called when reading an inaccessible property__set(string $name, mixed $value): void— Called when writing to an inaccessible property__isset(string $name): bool— Triggered byisset()orempty()__unset(string $name): void— Triggered byunset()
Example of __get() and __set():
<?php
class DynamicObject {
private array $data = [];
public function __get(string $name): mixed {
return $this->data[$name] ?? null;
}
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
}
$obj = new DynamicObject();
$obj->title = "Hello";
echo $obj->title; // Hello
Example of __isset() and __unset():
<?php
class DynamicObject {
private array $data = [];
public function __set(string $name, mixed $value): void {
$this->data[$name] = $value;
}
public function __isset(string $name): bool {
return isset($this->data[$name]);
}
public function __unset(string $name): void {
unset($this->data[$name]);
}
}
$obj = new DynamicObject();
$obj->name = "Test";
echo isset($obj->name) ? "exists" : "missing"; // exists
These methods enable dynamic properties, lazy loading, and flexible data containers while maintaining object-oriented structure.
Try it yourself
<?php
require_once 'Config.php';
// Read inputs
$settingName1 = trim(fgets(STDIN));
$settingValue = trim(fgets(STDIN));
$settingName2 = trim(fgets(STDIN));
// TODO: Create a Config instance
// TODO: Set the first setting to the given value
// TODO: Print whether the first setting exists ("exists" or "missing")
// TODO: Print the value of the first setting
// TODO: Print the current count of settings
// TODO: Use unset() to remove the first setting
// TODO: Print whether the first setting exists now ("exists" or "missing")
// TODO: Print the value of the second setting (which was never set)
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern