ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

php – do_action和add_action如何工作?

2019-10-01 01:39:45  阅读:227  来源: 互联网

标签:php wordpress wordpress-plugin


我试图找到do_action和add_action的确切作用.我已经用add_action检查了但是对于do_action我正在尝试新的.这是我试过的.

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以避免代码混乱问题.

    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

    }

所以我创建了另一个函数来指出钩子就像

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

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

谢谢.

解决方法:

它没有打印100的原因,因为anothertest()函数中的$regularprice是该函数的本地值.父mainplugin_test()函数中使用的变量$regularprice与anothertest()函数中使用的变量不同,它们位于不同的范围内.

因此,您需要在全局范围内定义$regularprice(这不是一个好主意),或者您可以将参数作为参数传递给do_action_ref_array.do_action_ref_array与do_action相同,而是接受第二个参数作为参数数组.

作为论点传递:

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');

标签:php,wordpress,wordpress-plugin
来源: https://codeday.me/bug/20191001/1837435.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有