7

I am using magento 1.8

And I am facing problem when I use below methods

$product->getData('name');

$product->getName();

Is they are same, I sure that they return same value[answer]. When I am using I am getting error

Fatal error: Call to a member function getData() on a non-object in

So may i know the exact difference between these two function.

Thank You,

2 Answers 2

11

They may be the same or they may be different. It depends on the object you are using.

If the class you instantiate contains the method getName() then the result you get from getName and getData('name') may be different.
You can even get an error if the class does not extend Varien_Object and does not have the method getData.

For classes that extend Varien_Object and do not contain the method getName() the results of the 2 methods are the same.
Varien_Object implements the method __call that is called if a certain method does not exist. See here how the code looks like.

So it basically maps the call of any method getSomethingHere() to getData('something_here'). It works the same for "fake" methods that start with set, has and uns.

More details provided here.

2
  • Good explain @Marius,i am give you upvote
    – Amit Bera
    Jun 13, 2014 at 6:59
  • @AmitBera. Thanks. same for you from my side.
    – Marius
    Jun 13, 2014 at 6:59
4

getData():

In most cases, this is the method you should use. Of the two options, this one is actually faster and more efficient. If you have no need to modify the output, and just want to display the value, use getData(). However, there are attributes that may not work properly with getData() such as the product price. Though I haven’t tested it yet, getData(‘name’) will most likely end up producing different results than getName().

getAttributeName()

You should really only use this method if you are needing to override the method in your block to add functionality to how the data is displayed/formatted. Magento needs to take some additional steps in rendering the data when you use this method, so it is a slightly slower process than displaying data using getData(). So, by using $_product->getName(), I am able to add a function to the product view block for example to modify the data before it is output to

Some details:https://stackoverflow.com/questions/3541273/magento-getsku-or-getdata-sku-returns-empty-string

3
  • 1
    I always use the second method because you never know when someone else will want to make an override. It is an important part of collaborative working. Oct 18, 2014 at 11:07
  • Can you please edit my answer
    – Amit Bera
    Oct 18, 2014 at 11:13
  • I don't think it's necessary to change your answer as I was only adding my opinion. Oct 18, 2014 at 11:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.