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().


Now if only PHP5 was universally supported…
Alex (Viper007Bond)
September 29, 2009 at 8:12 pm
Thats what the GoPHP5 project is for
http://www.gophp5.org/
Ramoonus
November 5, 2009 at 7:05 am
great work around
I sometimes forget to use the :: for my objects calling on there parents
justin
September 29, 2009 at 9:26 pm
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.
filosofo
October 2, 2009 at 10:20 am
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.
Mark Jaquith
October 6, 2009 at 6:04 am
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.
Jim Isaacs
November 17, 2009 at 2:20 am