PHP Classes and Objects Overriding Property Accesses - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Classes and Objects Overriding Property Accesses - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Sunday, May 26, 2019

PHP Classes and Objects Overriding Property Accesses

PHP Classes and Objects



Overriding Property Accesses

Problem

You want handler functions to execute whenever you read and write object properties. This lets you write generalized code to handle property access in your class.

Solution

Use the magic methods __get() and __set() to intercept property requests.

To improve this abstraction, also implement __isset() and __unset() methods to make the class behave correctly when you check a property using isset() or delete it using unset().

Discussion

Property overloading allows you to seamlessly obscure from the user the actual location of your object’s properties and the data structure you use to store them.

For example, the Person class stores variables in an array, $__data. (The name of the variable doesn’t need begin with two underscores, that’s just to indicate to you that it’s used by a magic method.)

           class Person {
                  private $__data = array();

                  public function __get($property) {
                         if (isset($this->__data[$property])) {
                                return $this->__data[$property];
                         } else {
                                return false;
                         }
                  }

                  public function __set($property, $value) {
                         $this->__data[$property] = $value;
                  }
           }

Use it like this:

           $johnwood = new Person;
           $johnwood->email = 'jonathan@wopr.mil';   // sets $user->__data['email']
           print $johnwood->email;                                // reads $user->__data['email']

           jonathan@wopr.mil

When you set data, __set() rewrites the element inside of $__data. Likewise, use __get() to trap the call and return the correct array element.

Using these methods and an array as the alternate variable storage source makes it less painful to implement object encapsulation. Instead of writing a pair of accessor methods for every class property, you use __get() and __set().

With __get() and __set(), you can use what appear to be public properties, such as $johnwood->name, without violating encapsulation. This is because the programmer isn’t reading from and writing to those properties directly, but is instead being routed through accessor methods.

The __get() method takes the property name as its single parameter. Within the method, you check to see whether that property has a value inside $__data. If it does, the method returns that value; otherwise, it returns false.

The __set() method takes two arguments: the property name and the new value. Otherwise, the logic inside the method is similar to __get().

Besides reducing the number of methods in your classes, these magical methods also make it easy to implement a centralized set of input and output validation.

Here’s how to also enforce exactly what properties are legal and illegal for a given class:

            class Person {
                  // list person and email as valid properties
                  protected $__data = array('person' => false, 'email' => false);

                  public function __get($property) {
                         if (isset($this->__data[$property])) {
                                return $this->__data[$property];
                         } else {
                                return false;
                         }
                  }

                  // enforce the restriction of only setting
                  // predefined properties
                  public function __set($property, $value) {
                         if (isset($this->__data[$property])) {
                                return $this->__data[$property] = $value;
                         } else {
                                return false;
                         }
                  }
            }

In this updated version of the code, you explicitly list the object’s valid property names when you define the $__data property. Then, inside __set(), you use isset() to confirm that all property writes are going to allowable names.

Preventing rogue reads and writes is why the visibility of the $__data property isn’t public, but protected. Otherwise, someone could do this:

            $person = new Person;
            $person->__data['fake_property'] = 'fake_data';

because the magical accessors aren’t used for existing properties.

Pay attention to this important implementation detail. In particular, if you’re expecting people to extend the class, they could introduce a property that conflicts with a property you’re expecting to handle using __get() and __set(). For that reason, the property in the earlier example is called $__data with two leading underscores.

You should consider prefixing all your “actual” properties in classes where you use magical accessors to prevent collisions between properties that should be handled using normal methods and ones that should be routed through __get() and __set().

There are three downsides to using __get() and __set(). First, these methods only catch missing properties. If you define a property for your class, __get() and __set() are not invoked by PHP when that property is accessed.

This is the case even if the property you’re trying to access isn’t visible in the current scope (for instance, when you’re reading a property that exists in the class but isn’t accessible to you, because it’s declared private). Doing this causes PHP to emit a fatal error:

            PHP Fatal error: Cannot access private property...

Second, these methods completely destroy any notion of property inheritance. If a parent object has a __get() method and you implement your own version of __get() in the child, your object won’t function correctly because the parent’s __get() method is never called.

You can work around this by calling parent::__get(), but it is something you need to explicitly manage instead of “getting for free” as part of OO design.

The illusion is incomplete because it doesn’t extend to the isset() and unset() methods. For instance, if you try to check if an overloaded property isset(), you will not get an accurate answer, as PHP doesn’t know to invoke __get().

You can fix this by implementing your own version of these methods in the class, called __isset() and __unset():

            class Person {
                   // list person and email as valid properties
                   protected $data = array('person' => false, 'email' => false);

                   public function __get($property) {
                         if (isset($this->data[$property])) {
                                return $this->data[$property];
                         } else {
                                return null;
                         }
                   }

                   // enforce the restriction of only setting
                   // pre-defined properties
                   public function __set($property, $value) {
                         if (isset($this->data[$property])) {
                                $this->data[$property] = $value;
                         }
                   }

                   public function __isset($property) {
                         return isset($this->data[$property]);
                   }

                   public function __unset($property) {
                         if (isset($this->data[$property])) {
                              unset($this->data[$property]);
                         }
                   }
            }

The __isset() method checks inside the $data element and returns true or false depending on the status of the property you’re checking.

Likewise, __unset() passes back the value of unset() applied to the real property, or false if it’s not set.

Implementing these two methods isn’t required when using __get() and __set(), but it’s best to do so because it’s hard to predict how you may use object properties. Failing to code these methods will lead to confusion when someone (perhaps even yourself) doesn’t know (or forgets) that this class is using magic accessor methods.

Other reasons to consider not using magical accessors are:


  • They’re relatively slow. They’re both slower than direct property access and explicitly writing accessor methods for all your properties.

  • They make it impossible for the Reflection classes and tools such as phpDocumentor to automatically document your code.


  • You cannot use them with static properties.


NOTE : When you read $johnwood->name, you actually call __get('name') and it’s returning $__data['name'], but for all external purposes that’s irrelevant.


No comments:

Post a Comment

Post Top Ad