Using PHP5 object constructors in WP Widget API

Someone mentioned to me that they couldn’t use PHP5-style object constructors when using the WP Widget API. I looked into it, and it turns out it does work. Example:

class My_Widget extends WP_Widget {
	function __construct() {
		$widget_ops = array( 'classname' => 'css-class', 'description' => 'Description' );
		parent::__construct( 'css-class', 'Title', $widget_ops );
	}
	// Rest of your widget subclass goes here
}

The key is using parent::__construct() instead of $this->WP_Widget().

16 thoughts on “Using PHP5 object constructors in WP Widget API

  1. It’s not clear from the example whether My_Widget’s PHP 4-style object-name constructor, “My_Widget()” is hiding in the “Rest of your widget subclass.” If you omit that it won’t work in PHP 4.

    When you leave off the object-name constructor “My_Widget()” in PHP 4, My_Widget’s parent object-name constructor, “WP_Widget,” becomes the constructor. And calling it directly as the constructor means you’ll be missing the necessary arguments.

    WP_Widget differs from WP_Dependencies, e.g., in this respect, in that WP_Dependencies’s object-name constructor has a hack that allows descendant objects to use PHP 5-style constructors alone.

  2. It’s not clear from the example whether My_Widget’s PHP 4-style object-name constructor, “My_Widget()” is hiding in the “Rest of your widget subclass.” If you omit that it won’t work in PHP 4.

    Yeah, this example was for PHP 5 only. For people who want to target both PHP 5 and PHP 4, it’s best to use the standard method, which most examples show.

  3. First of all, great job at WordCamp, I’m a NJ native that made my first appearance and had the pleasure of meeting you there. I was making my first rounds of most the communities blogs and scooting around here (congrats on the baby!) I found this post. I am commenting here because I actually have written a pretty robust php5 widget architecture that I am still in development on. There’s a lot of things I would like to do with it and I’m having that age old delema of finding a stopping point. Anyway, I was just wandering if this would be interesting to you or anyone to check out before a formal release. I hope I’m not imposing or anything like that, but I did dig into the widget architecture quite a bit and now I’m just curious of your thoughts on it and php5.

Comments are closed.