将一个函数中创建的PHP变量传递给另一个 [英] Pass PHP variable created in one function to another
本文介绍了将一个函数中创建的PHP变量传递给另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用wordpress和woocommerce(电子商务插件)来定制购物车。在我的functions.php中,我将数据存储在如下变量中:
add_action('woocommerce_before_calculate_totals','add_custom_price');
函数add_custom_price($ cart_object){
foreach($ cart_object-> cart_contents as $ key => $ value){
$ newVar = $ value ['data' ] - GT;价格;
}
}
我需要能够使用 $ newVar
在不同的函数中,所以我可以在页面的不同区域回显结果。例如,如果我有以下功能,我将如何在其中使用 $ newVar
?
add_action('another_area','function_name');
函数function_name(){
echo $ newVar;
}
我该怎么做?
function add_custom_price($ cart_object){
global $ newVar;
foreach($ cart_object-> cart_contents as $ key => $ value){
$ newVar = $ value ['data'] - > price;
函数function_name(){
global $ newVar;
echo $ newVar;
$ / code>
或者,如果 $ newVar
已在全球范围内可用:
函数function_name($ newVar){
echo $ newVar;
}
//添加钩子
add_action('another_area','function_name');
//用$ newVar触发钩子;
do_action('another_area',$ newVar);
I am using wordpress and woocommerce ( an e-commerce plugin) to customize a shopping cart. Within my functions.php I am storing data in a variable like so:
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$newVar = $value['data']->price;
}
}
I need to be able to use $newVar
in a different function so I can echo the result on a different area of the page. For instance, if I had the following function, how would I use $newVar
within it?
add_action( 'another_area', 'function_name' );
function function_name() {
echo $newVar;
}
How can I do this?
解决方案
You could make the variable global:
function add_custom_price( $cart_object ) {
global $newVar;
foreach ( $cart_object->cart_contents as $key => $value ) {
$newVar = $value['data']->price;
}
}
function function_name() {
global $newVar;
echo $newVar;
}
Or, if $newVar
is already available in the global scope you could do:
function function_name($newVar) {
echo $newVar;
}
// Add the hook
add_action( 'another_area', 'function_name' );
// Trigger the hook with the $newVar;
do_action('another_area', $newVar);
这篇关于将一个函数中创建的PHP变量传递给另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文