Bird
Raised Fist0
PHPprogramming~20 mins

__get and __set for property access in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
PHP Magic Property Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of __get magic method
What is the output of this PHP code when accessing the property $obj->name?
PHP
<?php
class Person {
    private $data = ['name' => 'Alice'];
    public function __get($prop) {
        return $this->data[$prop] ?? 'Unknown';
    }
}
$obj = new Person();
echo $obj->name;
AUnknown
Bnull
CError: Cannot access private property
DAlice
Attempts:
2 left
💡 Hint
The __get method returns the value from the private array if the property exists.
❓ Predict Output
intermediate
2:00remaining
Output when setting property with __set
What will be the output of this PHP code after setting $obj->age = 30; and then echoing $obj->age?
PHP
<?php
class Person {
    private $data = [];
    public function __set($prop, $value) {
        $this->data[$prop] = $value;
    }
    public function __get($prop) {
        return $this->data[$prop] ?? 'Not set';
    }
}
$obj = new Person();
$obj->age = 30;
echo $obj->age;
A30
BNot set
CError: Cannot access private property
Dnull
Attempts:
2 left
💡 Hint
The __set method stores the value in the private array, and __get retrieves it.
🔧 Debug
advanced
2:00remaining
Identify the error in __get usage
What error will this PHP code produce when trying to access $obj->city?
PHP
<?php
class Location {
    private $data = ['country' => 'USA'];
    public function __get($prop) {
        return $this->data[$prop];
    }
}
$obj = new Location();
echo $obj->city;
AFatal error: Cannot access private property
BNotice: Undefined index: city
Cnull
DUnknown
Attempts:
2 left
💡 Hint
Accessing an undefined array key without checking causes a notice.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error?
Which of the following __set method definitions will cause a syntax error in PHP?
Apublic function __set(string $name, mixed $value) { $this->data[$name] = $value; }
Bpublic function __set($name, $value) { $this->data[$name] = $value; }
Cpublic function __set($name $value) { $this->data[$name] = $value; }
Dpublic function __set($name, $value): void { $this->data[$name] = $value; }
Attempts:
2 left
💡 Hint
Check the parameter list syntax carefully.
🚀 Application
expert
3:00remaining
Count properties set via __set
Given this PHP class, what is the value of $obj->count after running the code below?
PHP
<?php
class Counter {
    private $data = [];
    private $count = 0;
    public function __set($name, $value) {
        $this->data[$name] = $value;
        $this->count++;
    }
    public function __get($name) {
        if ($name === 'count') {
            return $this->count;
        }
        return $this->data[$name] ?? null;
    }
}
$obj = new Counter();
$obj->a = 1;
$obj->b = 2;
$obj->a = 3;
echo $obj->count;
A3
BError
C1
D2
Attempts:
2 left
💡 Hint
Each __set call increments count, even if overwriting a property.

Practice

(1/5)
1.

What is the main purpose of the __get magic method in PHP?

easy
A. To control reading of inaccessible or undefined properties
B. To delete object properties
C. To initialize object properties automatically
D. To overload methods dynamically

Solution

  1. Step 1: Understand the role of __get

    The __get method is called when reading a property that is inaccessible or not defined in the object.
  2. Step 2: Compare with other options

    Options B, C, and D describe different behaviors unrelated to __get. Only To control reading of inaccessible or undefined properties correctly describes its purpose.
  3. Final Answer:

    To control reading of inaccessible or undefined properties -> Option A
  4. Quick Check:

    __get reads missing properties = A [OK]
Hint: Remember __get triggers on reading missing properties [OK]
Common Mistakes:
  • Confusing __get with __set
  • Thinking __get initializes properties
  • Assuming __get deletes properties
2.

Which of the following is the correct syntax to define the __set magic method in a PHP class?

class Example {
    ?
}
easy
A. public function __set($name, $value) { /* code */ }
B. public function __set($value, $name) { /* code */ }
C. public function __set() { /* code */ }
D. public function set($name, $value) { /* code */ }

Solution

  1. Step 1: Recall __set method signature

    The __set method must accept two parameters: the property name and the value to assign.
  2. Step 2: Check parameter order and method name

    public function __set($name, $value) { /* code */ } correctly uses __set($name, $value). public function __set($value, $name) { /* code */ } reverses parameters, C has no parameters, and D uses wrong method name.
  3. Final Answer:

    public function __set($name, $value) { /* code */ } -> Option A
  4. Quick Check:

    __set($name, $value) correct signature = B [OK]
Hint: __set always takes property name first, then value [OK]
Common Mistakes:
  • Swapping parameter order
  • Omitting parameters
  • Using wrong method name without double underscore
3.

What will be the output of the following PHP code?

class Test {
    private $data = [];
    public function __set($name, $value) {
        $this->data[$name] = $value;
    }
    public function __get($name) {
        return $this->data[$name] ?? 'Not found';
    }
}

$obj = new Test();
$obj->color = 'red';
echo $obj->color . ' ' . $obj->size;
medium
A. red null
B. red Not found
C. Notice error and red
D. red

Solution

  1. Step 1: Understand property setting

    Setting $obj->color = 'red' calls __set, storing 'red' in $data['color'].
  2. Step 2: Understand property getting

    Accessing $obj->color returns 'red'. Accessing $obj->size returns 'Not found' because $data['size'] is not set.
  3. Final Answer:

    red Not found -> Option B
  4. Quick Check:

    Defined property returns value, undefined returns 'Not found' = D [OK]
Hint: Undefined property returns default from __get using ?? operator [OK]
Common Mistakes:
  • Expecting undefined property to be empty string
  • Ignoring null coalescing operator
  • Assuming Notice error on missing array key
4.

Consider this PHP class:

class Sample {
    private $props = [];
    public function __set($name, $value) {
        $this->props[$name] = $value;
    }
    public function __get($name) {
        return $this->props[$name];
    }
}

$obj = new Sample();
echo $obj->missing;

What error will occur and how to fix it?

medium
A. No error; outputs empty string
B. Fatal error; fix by declaring property publicly
C. Parse error; fix by adding return type
D. Undefined index notice; fix by using null coalescing in __get

Solution

  1. Step 1: Identify error cause

    Accessing $obj->missing calls __get, which returns $this->props['missing']. Since 'missing' key is not set, PHP raises an undefined index notice.
  2. Step 2: Fix the error

    Modify __get to return $this->props[$name] ?? null or a default value to avoid notice.
  3. Final Answer:

    Undefined index notice; fix by using null coalescing in __get -> Option D
  4. Quick Check:

    Missing key causes notice; use ?? to fix = C [OK]
Hint: Use ?? operator in __get to avoid undefined index notices [OK]
Common Mistakes:
  • Ignoring undefined index notices
  • Trying to declare missing properties publicly
  • Confusing parse errors with runtime notices
5.

You want to create a PHP class that stores any property set dynamically and logs every property read or write. Which implementation correctly uses __get and __set to achieve this?

class Logger {
    private $data = [];
    public function __set($name, $value) {
        // ???
    }
    public function __get($name) {
        // ???
    }
}
hard
A. In __set: echo write log only; in __get: return value without logging
B. In __set: only store value; in __get: return value without logging
C. In __set: store value and echo write log; in __get: echo read log and return value or null
D. In __set: store value and return it; in __get: echo read log only

Solution

  1. Step 1: Understand logging requirements

    We must log both property writes and reads, and store values dynamically.
  2. Step 2: Check each option's behavior

    In __set: store value and echo write log; in __get: echo read log and return value or null stores the value in $data and echoes a write log in __set, and echoes a read log and returns the stored value or null in __get. This meets all requirements.
  3. Final Answer:

    In __set: store value and echo write log; in __get: echo read log and return value or null -> Option C
  4. Quick Check:

    Store and log on read/write = A [OK]
Hint: Log inside both __get and __set while storing values [OK]
Common Mistakes:
  • Logging only on write or only on read
  • Not returning value in __get
  • Returning value in __set (which should be void)
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard