0
0
PHPprogramming~20 mins

__get and __set for property access in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
__get and __set for property access in PHP
📖 Scenario: Imagine you are creating a simple PHP class to manage a user's profile. You want to control how properties are accessed and changed, even if they are not directly defined in the class.
🎯 Goal: Build a PHP class called UserProfile that uses __get and __set magic methods to manage property access and updates.
📋 What You'll Learn
Create a class UserProfile with a private array data to store properties.
Add a __get method to retrieve values from data.
Add a __set method to update values in data.
Demonstrate setting and getting properties using the magic methods.
💡 Why This Matters
🌍 Real World
Many PHP frameworks and libraries use <code>__get</code> and <code>__set</code> to manage object properties dynamically, such as in ORM (Object-Relational Mapping) or configuration classes.
💼 Career
Understanding magic methods like <code>__get</code> and <code>__set</code> is important for PHP developers working on modern applications that require flexible and secure property management.
Progress0 / 4 steps
1
Create the UserProfile class with private data array
Create a PHP class called UserProfile with a private property data initialized as an empty array.
PHP
Need a hint?

Use private array $data = []; inside the class to store properties.

2
Add the __get magic method
Inside the UserProfile class, add a public method __get that takes a string $name and returns the value from $this->data[$name] if it exists, or null otherwise.
PHP
Need a hint?

Use the null coalescing operator ?? to return null if the key is not set.

3
Add the __set magic method
Inside the UserProfile class, add a public method __set that takes a string $name and a mixed $value, and sets $this->data[$name] to $value.
PHP
Need a hint?

Assign the $value to the $name key in the $data array.

4
Create an instance and test property access
Create an instance of UserProfile called $user. Use $user->name = "Alice"; to set the name, and then print $user->name using echo.
PHP
Need a hint?

Use echo $user->name; to display the stored name.