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 = 'test@test.com'; // 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.

Link to comment
Share on other sites

__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.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.