简体   繁体   中英

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.

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

If you're using PHP 5.4, it's already a callable:

$contextAndFunction();

Here's a demo.

Otherwise, call_user_func will work as-is.

call_user_func($contextAndFunction);

And there's a demo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM