0
0
PHPprogramming~5 mins

__get and __set for property access in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the __get magic method in PHP?
The __get method is called when reading data from non-existing properties. It allows you to control what happens when you try to access such properties.
Click to reveal answer
beginner
What does the __set magic method do in PHP?
The __set method is called when writing data to non-existing properties. It lets you define how to handle setting values to those properties.
Click to reveal answer
intermediate
How do __get and __set help with property access in PHP classes?
They let you control reading and writing to non-existing properties, making your class flexible and secure by managing property access.
Click to reveal answer
beginner
Show a simple example of using __get and __set in a PHP class.
class Person {
  private $data = [];
  public function __get($name) {
    return $this->data[$name] ?? null;
  }
  public function __set($name, $value) {
    $this->data[$name] = $value;
  }
}

$person = new Person();
$person->name = 'Alice';
echo $person->name; // Outputs: Alice
Click to reveal answer
intermediate
What happens if you try to access a property that does not exist and __get is not defined?
PHP will trigger a notice about an undefined property and return NULL. Defining __get lets you handle this situation gracefully.
Click to reveal answer
Which magic method is called when you try to read a non-existing property in PHP?
A__get
B__set
C__call
D__construct
What does the __set method allow you to do?
AControl how to read properties
BControl how to write to properties
CCall methods dynamically
DInitialize the object
If a class has __get and __set methods, what happens when you access a non-existing property?
A__get and __set handle the access
BPHP throws a fatal error
CThe property is accessed directly
DThe property is ignored
What will this code output? class Test { private $data = []; public function __get($name) { return $this->data[$name] ?? 'Not set'; } public function __set($name, $value) { $this->data[$name] = $value; } } $t = new Test(); echo $t->color;
ANULL
Bcolor
CNot set
DError
Why might you use __get and __set instead of public properties?
ATo make code slower
BTo make properties global
CTo avoid writing any code
DTo control and validate property access
Explain how __get and __set magic methods work in PHP and why they are useful.
Think about what happens when you try to read or write a property that is not public.
You got /4 concepts.
    Write a simple PHP class using __get and __set to store property values in a private array.
    Use an array inside the class to save property values dynamically.
    You got /4 concepts.