0

I am new to wordpress and following a tutorial to create a new widget. I have noticed in some situations $instance variable is used and some situations $this is used. Like

$instance['title']

$this->get_field_id( 'title' )

I know first line returns the title value and second line returns the id of the field. But ins't $this means the instantiated object of the class? Why do I have to use $instance variable too? Can't we use $this to get title value of widget?

1 Answer 1

0

The WP_Widget class can be a bit confusing as an object instance of it (a child class must be used) doesn't represent a specific instance of a widget. It is more of an object to handle all instances of this widget class.

$instance is a variable repeatedly used within the WP_Widget class (and hence also in all child classes). It doesn't actually hold a reference to an instance of a php Object. Instead it is just an array with settings for an incarnation of a WordPress widget. This array() gets saved to the DB and retrieved again to be able to save the settings for the different widgets.

$this is a pseudo-variable which references the current instantiation of the widget class. So this is actually a reference to a php object instance, but it is not for a specific widget instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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