PHP __get() And __set(): Exploring Their Working and Usage

In this tutorial you will learn about PHP __get() and __set() methods, how they works and when to use.

What are __get() And __set()

In PHP there are some special functions that are automatically invoked or called by the interpreter in response to specific events or actions within an object, these methods or functions are called magic methods.

There are various magic methods in PHP that provide a way to customize the behavior of classes and objects, making it possible to implement functionalities beyond the standard methods. Two of them are __get() and __set().

Note: Magic methods are recognized by their names starting with a double underscore __. For example, __construct(), __destruct(), __get(), and __set() are all magic methods.

Working of __get() And __set()

Magic methods are called automatically, so now the question is when __get and __set are invoked, I mean in which event these methods are triggered?

The answer is – the “__get()” and “__set()” methods are primarily used to control access to object properties. Therefore these methods are invoked when an object try to access inaccessible properties of the class.

1. The __get() Method

The __get() method triggered when an attempt is made to “access a propertythat is not accessible (because the property is private or protected) or does not exist.

<?php
// Define Test class
class Test{
    // Public property
    public $name = "John";
    // Private property
    private $email = "[email protected]";

    // Magic method to intercept property access
    function __get($var_name){
        // Return a message when trying to access inaccessible properties
        return "Hi from get method. You cannot access the \"{$var_name}\" property.";        
    }
}

// Create an instance of the Test class
$obj = new Test();

// Access the public property
echo $obj->name."\n";

// Access the private property (will trigger the __get method)
echo $obj->email;
John
Hi from get method. You cannot access the "email" property.

2. The __set() Method

The __set() method triggered when an attempt is made to “assign a valueto an inaccessible property (because the property is private or protected) or nonexistent property.

<?php
// Define Test class
class Test{
    // Public property
    public $name = "John";
    // Private property
    private $email = "[email protected]";
    
    // Magic method to intercept property assignment
    function __set($var_name, $value){     
        // Display error message when trying to set inaccessible properties
        echo "You cannot assign \"$value\" to the \"$var_name\" variable.";
    }
}

// Create an instance of the Test class
$obj = new Test();

// Try to modify the public property
$obj->name = "Raju";

// Try to modify the private property (will trigger the __set method)
$obj->email = "[email protected]";
You cannot assign "[email protected]" to the "email" variable.

Use Cases of __get And__set:

__get Usage:

  • Dynamic Property Access: You can use __get to implement dynamic property access, where properties are accessed in a controlled manner. This can be useful for accessing private or protected properties indirectly.
  • Lazy Loading: When dealing with large datasets or expensive resources, you can use __get to load them only when accessed. This allows for lazy initialization of properties, improving performance.
  • Magic Methods for Property Access: __get can be used to implement custom behavior when accessing properties, such as logging, validation, or data transformation.

__set Usage:

  • Property Validation: You can use __set to validate property values before assigning them. This ensures that only valid values are assigned to properties, helping maintain data integrity.
  • Data Sanitization: Before assigning values to properties, you can sanitize or format them using __set. This helps prevent security vulnerabilities like SQL injection by cleaning user input.
  • Implementing Access Control: __set can be used to enforce access control by restricting the assignment of certain properties. This is useful for implementing read-only or write-only properties.
  • Dynamic Properties: You can use __set to implement dynamic properties, where properties are created dynamically based on assignment. This can be useful for scenarios where the number or names of properties are not known in advance.
class Example {
    private $data = [];

    // __get magic method for property access
    public function __get($name) {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        } else {
            return "Property '$name' does not exist.";
        }
    }

    // __set magic method for property assignment
    public function __set($name, $value) {
        // Example: Validation
        if ($name === 'age' && !is_int($value)) {
            throw new InvalidArgumentException("Age must be an integer.");
        }

        // Example: Sanitization
        if ($name === 'name') {
            $value = htmlspecialchars($value);
        }

        $this->data[$name] = $value;
    }
}

// Usage
$obj = new Example();
$obj->name = "<script>alert('Hello');</script>"; // Sanitization
echo $obj->name; // Outputs: &lt;script&gt;alert('Hello');&lt;/script&gt;
$obj->age = "30"; // Validation
echo $obj->age; // Outputs: Property 'age' does not exist.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy