do_action和add_action如何工作? [英] How do do_action and add_action work?

查看:133
本文介绍了do_action和add_action如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图找到do_action和add_action到底能做什么.我已经使用add_action进行了检查,但是对于do_action我正在尝试尝试新的方法.这是我尝试过的.

I am trying to find what exactly do_action and add_action works. I already examine with add_action but for do_action i am trying as new now. This what i tried.

function mainplugin_test() {

$regularprice = 50;

if(class_exists('rs_dynamic')) {
$regularprice = 100;
}

// and doing further
//like i echoing the regular price
echo $regularprice; //It print 100 from this code

}

现在,我打算在主文件中创建一些do_action以避免代码混乱问题,而不是在主文件中放置少量代码.

Now instead of placing few code in main file i am planning to create do_action to avoid code messing issue.

    function mainplugin_test() {

    $regularprice = 50;

    do_action('testinghook');

// and doing further
//like i echoing the regular price
echo $regularprice; //It should print 100 but it print 50

    }

所以我创建了另一个函数以指出该钩子是类似的

so i created another function to point out that hook as something like

function anothertest() {
if(class_exists('rs_dynamic')) {
$regularprice = 100;
}
}
add_action('testinghook','anothertest');

不确定如何向上面的函数可能起作用的那个钩子添加代码行?按照我在测试环境中尝试过的方法,没有任何帮助.如果我理解正确的do_action更像是包含一个文件???如果没有,请告诉我.

Not sure how to add the lines of code to that hook that above function may work? As per i tried in my testing environment nothing helps. If i understand correct do_action is more like including a file??? If not please advise me.

谢谢.

推荐答案

之所以没有打印100,是因为anothertest()函数中的$regularprice是该函数的本地变量.父mainplugin_test()函数中使用的变量$regularpriceanothertest()函数中使用的变量不同,它们在单独的范围内.

The reason it didn't print 100, because $regularprice within anothertest() function is local to that function. The variable $regularprice used in parent mainplugin_test() function is not same as the variable used in anothertest() function, they are in separate scope.

因此,您需要在全局范围内定义$regularprice(这不是一个好主意),也可以将参数作为参数传递给

So you need to either define the $regularprice in a global scope (which is not a good idea) or you can pass argument as a parameter to do_action_ref_array. The do_action_ref_array is the same as do_action instead it accepts second parameter as array of parameters.

function mainplugin_test() {

    $regularprice = 50;

    // passing as argument as reference
    do_action_ref_array('testinghook', array(&$regularprice));

    echo $regularprice; //It should print 100

}

// passing variable by reference
function anothertest(&$regularprice) {
    if(class_exists('rs_dynamic')) {
        $regularprice = 100;
    }
}
// remain same
add_action('testinghook','anothertest');

这篇关于do_action和add_action如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆