top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What are “magic methods” in Magento?

0 votes
635 views
What are “magic methods” in Magento?
posted Feb 28, 2018 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Magic Methods inside Magento are methods that are called to check, retrieve, set, or unset data. So, basically, you can fetch any data from the protected $_data array in an object simply by calling an appropriate Magic Method.
How it works is basically through the use of the Varien_Object class. Inside this class, it utilizes the __call() method as a last resort whenever it cannot find a method you called. The details look like :

   /**
  * Set/Get attribute wrapper
  *
  * @param   string $method
  * @param   array $args
  * @return  mixed
  */
 public function __call($method, $args)

 {
     switch (substr($method, 0, 3)) {
         case 'get' :
             //Varien_Profiler::start('GETTER: '.get_class($this).'::'.$method);
             $key = $this->_underscore(substr($method,3));
             $data = $this->getData($key, isset($args[0]) ? $args[0] : null);
             //Varien_Profiler::stop('GETTER: '.get_class($this).'::'.$method);
             return $data;

     case 'set' :
         //Varien_Profiler::start('SETTER: '.get_class($this).'::'.$method);
         $key = $this->_underscore(substr($method,3));
         $result = $this->setData($key, isset($args[0]) ? $args[0] : null);
         //Varien_Profiler::stop('SETTER: '.get_class($this).'::'.$method);
         return $result;

     case 'uns' :
         //Varien_Profiler::start('UNS: '.get_class($this).'::'.$method);
         $key = $this->_underscore(substr($method,3));
         $result = $this->unsetData($key);
         //Varien_Profiler::stop('UNS: '.get_class($this).'::'.$method);
         return $result;

     case 'has' :
         //Varien_Profiler::start('HAS: '.get_class($this).'::'.$method);
         $key = $this->_underscore(substr($method,3));
         //Varien_Profiler::stop('HAS: '.get_class($this).'::'.$method);


           return isset($this->_data[$key]);
     }
     throw new Varien_Exception("Invalid method ".get_class($this)."::".$method."(".print_r($args,1).")");
 }

Every Model in Magento basically derives from this class so you can use magic methods (just about) anywhere.

Let’s take a simple example. You are fetching a product name within a class. You call the method:

$this->getName();

Hope this will help you. Thanks

answer Feb 28, 2018 by Vishi Gulati
...