Magic methods let PHP objects do special things automatically. They help make code easier and cleaner by handling common tasks behind the scenes.
Why magic methods exist in PHP
<?php class MyClass { public function __construct() { // Code runs when object is created } public function __destruct() { // Code runs when object is destroyed } public function __get($name) { // Code runs when getting a property that does not exist } public function __set($name, $value) { // Code runs when setting a property that does not exist } public function __toString() { // Code runs when object is used as a string return ""; } public function __call($name, $arguments) { // Code runs when calling a method that does not exist } } ?>
Magic methods always start with two underscores (__).
They are called automatically by PHP in special situations.
<?php class Person { private $data = []; public function __set($name, $value) { $this->data[$name] = $value; } public function __get($name) { return $this->data[$name] ?? 'Not set'; } } $person = new Person(); $person->age = 30; echo $person->age; ?>
<?php class Logger { public function __construct() { echo "Logger started\n"; } public function __destruct() { echo "Logger stopped\n"; } } $log = new Logger(); ?>
<?php class Message { public function __toString() { return "Hello from Message!"; } } $msg = new Message(); echo $msg; ?>
This program shows magic methods working together: constructor, setter, getter, toString, and destructor. It prints messages automatically when properties are set or accessed, and when the object is created or destroyed.
<?php class MagicDemo { private $properties = []; public function __construct() { echo "Object created\n"; } public function __set($name, $value) { echo "Setting '$name' to '$value'\n"; $this->properties[$name] = $value; } public function __get($name) { echo "Getting '$name'\n"; return $this->properties[$name] ?? "Property '$name' not found"; } public function __toString() { return "MagicDemo object with properties: " . implode(", ", array_keys($this->properties)); } public function __destruct() { echo "Object destroyed\n"; } } $demo = new MagicDemo(); $demo->color = 'blue'; echo $demo->color . "\n"; echo $demo . "\n"; ?>
Magic methods help you write less code for common tasks.
They make your objects behave more like built-in types.
Use them carefully to keep code clear and easy to understand.
Magic methods run automatically in special situations.
They help manage object creation, property access, method calls, and string conversion.
Using magic methods can make your code cleaner and more flexible.
Practice
Solution
Step 1: Understand the role of magic methods
Magic methods are special functions that PHP calls automatically in certain situations, like when creating objects or accessing properties.Step 2: Identify their purpose
They help manage object behaviors automatically, making code cleaner and more flexible without replacing all normal methods or preventing object creation.Final Answer:
To automatically handle special object behaviors like creation and property access -> Option BQuick Check:
Magic methods = automatic special behavior [OK]
- Thinking magic methods replace all normal methods
- Believing magic methods speed up PHP execution
- Assuming magic methods stop object creation
Solution
Step 1: Recall the constructor magic method name
The magic method for object creation in PHP is named exactly __construct with two underscores.Step 2: Check syntax correctness
Only function __construct() {} uses the correct double underscore and spelling; others are invalid or not magic methods.Final Answer:
function __construct() {} -> Option DQuick Check:
Constructor magic method = __construct [OK]
- Using single underscore instead of double
- Misspelling the method name
- Confusing __construct with __create
$obj = new class {
public function __toString() {
return "Hello!";
}
};
echo $obj;Solution
Step 1: Understand __toString magic method
The __toString method defines how an object converts to a string when echoed or printed.Step 2: Analyze the code output
The anonymous class defines __toString returning "Hello!", so echoing the object prints "Hello!".Final Answer:
Hello! -> Option AQuick Check:
__toString returns string output [OK]
- Expecting an error without __toString
- Thinking it prints 'Object' by default
- Assuming NULL is printed
class Test {
public function __get($name) {
return $this->$name;
}
}
$obj = new Test();
echo $obj->value;Solution
Step 1: Understand __get behavior in this code
The __get method tries to return $this->$name, but accessing $this->$name triggers __get again.Step 2: Identify the problem
This causes infinite recursion because __get calls itself repeatedly without a base case or existing property.Final Answer:
Infinite recursion causing error -> Option CQuick Check:
__get calling itself = infinite recursion [OK]
- Thinking __get has syntax errors
- Assuming no error occurs
- Confusing __get with __set
Solution
Step 1: Identify magic methods for property access and setting
__get is called when reading inaccessible properties, __set when writing them.Step 2: Match methods to logging requirement
Using __get and __set lets you add logging code centrally for all properties without manual code per property.Final Answer:
__get and __set -> Option AQuick Check:
Property access logging = __get + __set [OK]
- Confusing __call with property access
- Using __construct which runs only once
- Thinking __toString handles properties
Ready to prove it?
Pass the test and this pattern moves unknown
