php add action,php – do_action和add_action如何工作?

我试图找到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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值