How can I call a custom function that is part of a class in PHP (wordpress do_action style)?

WordPress uses hooks and actions for extensibility. A plugin might look something like this:

class myLightbox
{
    function __construct()
    {
        add_action('wp_footer',array($this,'my_footer'));
    }

    function my_footer()
    {
        echo '<script src="http://external-site.com/lightbox.js" ></script>';
    }
}

If I run that code outside of WordPress, I’d like the add_action to work – even if it just calls the function immediately.

Read More

I read these:

The second one is fairly close to what I’d like to do, but I don’t think it was designed to work with functions that are part of a class.

I tried using call_user_function but I’m not sure how to give it the array($this,'my_footer') stuff:

function add_action($whenToCall,$contextAndFunction=array())
{
    call_user_func($contextAndFunction);
}

I also tried this, but as you can tell my OOP isn’t great so I’m struggling:

function add_action($whenToCall,$contextAndFunction=array())
{
    $function = array_pop($contextAndFunction);
    $context = array_pop($contextAndFunction);

    $context->$function();

}

Failed test using minitech‘s suggestion:

class myLightbox
{
    function __construct()
    {
        add_action('wp_footer',array($this,'my_footer'));
    }

    function my_footer()
    {
        echo '<script src="http://external-site.com/lightbox.js" ></script>';
    }
}


function add_action($whenToCall,$contextAndFunction=array())
{
    $contextAndFunction();
}


$myLightbox = new myLightbox();

Produces:

Fatal error: Function name must be a string

Related posts

Leave a Reply

1 comment