0
0
PHPprogramming~10 mins

__get and __set for property access in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define the magic method that is called when reading inaccessible properties.

PHP
<?php
class Person {
    private $data = [];

    public function [1]($name) {
        return $this->data[$name] ?? null;
    }
}
?>
Drag options to blanks, or click blank then click option'
A__construct
B__call
C__get
D__set
Attempts:
3 left
💡 Hint
Common Mistakes
Using __set instead of __get for reading properties.
Forgetting the $name parameter.
2fill in blank
medium

Complete the code to define the magic method that is called when writing to inaccessible properties.

PHP
<?php
class Person {
    private $data = [];

    public function [1]($name, $value) {
        $this->data[$name] = $value;
    }
}
?>
Drag options to blanks, or click blank then click option'
A__unset
B__get
C__call
D__set
Attempts:
3 left
💡 Hint
Common Mistakes
Using __get instead of __set for writing properties.
Missing the $value parameter.
3fill in blank
hard

Fix the error in the magic method name to correctly handle property reading.

PHP
<?php
class Person {
    private $data = [];

    public function [1]($name) {
        return $this->data[$name] ?? null;
    }
}
?>
Drag options to blanks, or click blank then click option'
A__set
B__get
C__gett
D__call
Attempts:
3 left
💡 Hint
Common Mistakes
Misspelling the method as __gett or __gett.
Using __set instead of __get.
4fill in blank
hard

Fill both blanks to complete the magic methods for property access.

PHP
<?php
class Person {
    private $data = [];

    public function [1]($name) {
        return $this->data[$name] ?? null;
    }

    public function [2]($name, $value) {
        $this->data[$name] = $value;
    }
}
?>
Drag options to blanks, or click blank then click option'
A__get
B__set
C__call
D__unset
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the method names.
Using unrelated magic methods like __call or __unset.
5fill in blank
hard

Fill all three blanks to create a class that uses __get and __set to store and retrieve properties in a private array.

PHP
<?php
class DataStore {
    private $storage = [];

    public function [1]($key) {
        return $this->storage[[2]] ?? null;
    }

    public function [3]($key, $value) {
        $this->storage[$key] = $value;
    }
}
?>
Drag options to blanks, or click blank then click option'
A__get
B$key
C__set
D$value
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names inside the array access.
Confusing __get and __set method names.