简体   繁体   English

如何从 function 中检索变量?

[英]How can I retrieve a variable from a function?

I know there are a few items out on the internet over how to achieve this, but I can't get it to work... Can anyone please point me in the right direction?我知道互联网上有一些关于如何实现这一目标的项目,但我无法让它发挥作用......谁能指出我正确的方向?

I currently have two functions.我目前有两个功能。 I want to use the variable ( $new_data ) from function1 inside function2.我想在函数 2 中使用来自函数 1 的变量( $new_data )。

Function 1: Function 1:

function manipulate_form_submission( $record, $ajax_handler ) {
    $form_name = $record->get_form_settings( 'form_name' );
    $form_data = $record->get( 'fields' );
    
    //change the names of fields before we send them somewhere
    $new_data = array(
        'email'         => isset( $form_data['email']['value'] ) ? $form_data['email']['value'] : '',
        'url'           => isset( $form_data['url']['value'] ) ? $form_data['url']['value'] : ''
    )
}

Function 2: Function 2:

add_action( 'woocommerce_payment_complete', 'so_payment_complete' );
function so_payment_complete( $order_id ){
    $order = wc_get_order( $order_id );
    $response = wp_remote_post( 'https://mywebsite.com/insert_values.php', array( 'body' => $new_data) );
    
}

Thanks in advance!提前致谢!

Just initialize the variable outside the two functions like this:只需像这样在两个函数之外初始化变量:

<?php
$new_data = false;
function manipulate_form_submission( $record, $ajax_handler ) {
    global $new_data;
    $new_data = "New value";
}
function so_payment_complete( $order_id ){
    // The variable is accessible here
    global $new_data;
    echo $new_data;
}
?>

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

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