How do I expand the scope of a PHP variable?

I am running a query in WordPress and need to reuse a variable $my_query_results

later in my script.

function init() {

    $args = array(
        'post_type' => 'post'
    );
    $my_query_results = new WP_Query( $args );
}

      

-

function process() {
    // I need to process $my_query_results here.
}
add_action( 'wp_ajax_myaction', 'process' );

      

I don't want to rerun the request internally process()

. How do I make it $my_query_results

available to a function process()

?

Background info: The function process()

handles data sent via an AJAX request. After processing, it sends a response to the browser. For example:echo json_encode( $response )

+3


source to share


3 answers


If these functions are present in the same class, you can assign it to the class:



class Class
{
    public $my_query_results;

    function init(){
        $args = array(
            'post_type' => 'post'
        );
        $this->my_query_results = new WP_Query( $args );
    }
    function process() {
        // access $this->my_query_results
    }
}

      

+5


source


You can pass a variable as a parameter

function init(&$my_query_results) {

    $args = array(
        'post_type' => 'post'
    );
    $my_query_results = new WP_Query( $args );
}

function process(&$my_query_results) {
    // I need to process $my_query_results here.
}

      



Using

init($my_query_results);
process($my_query_results);

      

+1


source


or you can just execute a global variable:

$my_query_results = null;
function init() {

$args = array(
    'post_type' => 'post'
);
$my_query_results = new WP_Query( $args );

      

}

-3


source







All Articles