[wp-hackers] Need WP/PHP guru eyeballs/feedback on my WP_Widget wrapper class

Micky Hulse mickyhulse.lists at gmail.com
Tue Jun 25 20:33:02 UTC 2013


On Tue, Jun 25, 2013 at 11:20 AM, Micky Hulse
<mickyhulse.lists at gmail.com> wrote:
> Thanks for the kick in the pants! :)

Well, here's a new version of my code:

https://gist.github.com/mhulse/5861847

I tried to boil it down to just the basics.

Now that I've simplified the code, I think I discovered a core problem:

----------

In Foo_Widget's constructor, this works:

parent::__construct('eeeeeeeeee', 'wtf son?', $widget_ops, $control_ops);

... but this does not:

parent::__construct($id_base, $name, $widget_ops, $control_ops);

Why can't I pass $id_base and $name as string variables to the parent
WP_Widget constructor?

----------

I feel like the above issue could be the root of my problems.

Another question:

----------

In Foo_Widget's constructor, if I do this:

... __construct($arr) ...

I get this PHP notice:

"Undefined variable: arr in /.../class.foo_widget.php on line 9".

If I change the constructor to this:

... __construct($arr = array()) ...

... the PHP notice goes away.

Why does this happen?

Shouldn't $arr be defined by the time it reaches line #9? Is this a WP
timing thing, or just a general PHP5 OOP constructor thing that I've
never been privy to? :D

I don't mind setting a default argument value here, it just feels
overkill and I've never run into this type of "notice" before.

----------

With all that said, I hope you folks can see what I'm trying to do.
Basically, I would like to wrap WP_Widget in a Class which has some
customizations, and then call my custom widget class like so:


[code]

include_once('class.foo_widget.php');

$foo_test_widget_1 = new Foo_Widget(
    array(
        'id_base' => 'foo_test_widget_1',
        'name' => 'Foo Test Widget 1'
    )
);

$foo_test_widget_2 = new Foo_Widget(
    array(
        'id_base' => 'foo_test_widget_2',
        'name' => 'Foo Test Widget 2'
    )
);

[/code]

... and so on.

Maybe what I'm trying to do isn't feasible? All the examples I've seen
show a new class for each new widget; this is what I'm doing now, and
that technique works great ... I just thought it would be even better
if I could create new widgets using the syntax above (i.e. one custom
widget class that extends WP_Widget where the name/title/other are
passed during instantiation).

I hope that helps to clarify what I'm trying to do.

I guess, at this point, I'm look for tips ... I feel like I'm close to
getting this code to work ... I'm kinda confused as to why I can't
seem to pass variables to the WP_Widget constructor but hard-coded
strings work no problems.

Thanks for listening.

Micky


More information about the wp-hackers mailing list