Jump to content

What's the point of __set and __get?


LemonInflux

Recommended Posts

using __set and __get magic methods can have all sorts of nice uses. personally i use it for 'models'. So:

 

<?php
class User
{
   private $data = array(); // holds user record data

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

   public function __get($varname) {
      return isset($this->data[$varname]) ? $this->data[$varname] : null;
   }
}

$user = new User();

$user->email = '[email protected]'; // sets User::$data['email']
?>

 

this way, i know that the $data property ONLY holds info about the user, not tonnes of other unrelated properties.

You can also use these magic setters and getters to control what can or cannot be set from outside the class - ie, enforcing a certain way of using your class.

__set and __get methods are mainly used for open ended data structures, and generally breaks encapsulation (because every class property is now essentially public.) As you can see, the main draw back is the developer using your API can add properties to a class at their leisure.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.