简体   繁体   English

如何调用PHP类中的自定义函数(wordpress do_action样式)?

[英]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. WordPress使用钩子和操作来实现可扩展性。 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. 如果我在Wordpress之外运行该代码,我希望add_action可以工作-即使它只是立即调用该函数。

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: 我尝试使用call_user_function但是我不确定如何给它提供array($this,'my_footer')东西:

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: 我也尝试过此方法,但是正如您所知,我的OOP不好,所以我很努力:

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

    $context->$function();

}

Failed test using minitech 's suggestion: 使用minitech的建议测试失败:

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: 如果您使用的是PHP 5.4,则已经可以调用了:

$contextAndFunction();

Here's a demo. 这是一个演示。

Otherwise, call_user_func will work as-is. 否则, call_user_func将按原样工作。

call_user_func($contextAndFunction);

And there's a demo. 还有的演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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