代码之家  ›  专栏  ›  技术社区  ›  henrywright

如何扩大变量PHP的范围?

  •  3
  • henrywright  · 技术社区  · 11 年前

    我正在WordPress中运行查询,需要重新使用 $my_query_results 变量。

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

    我不想在内部重新运行查询 process() 我该怎么做 $my_query_results($my_查询结果) 可用于 进程() 作用

    背景信息: 这个 进程() 函数处理通过AJAX请求发送的数据。处理后,它会向浏览器发送响应。例如: echo json_encode( $response )

    3 回复  |  直到 11 年前
        1
  •  5
  •   Stefan Van den Heuvel    11 年前

    如果这些函数存在于同一类中,则可以将其分配给类属性:

    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
        }
    }
    
        2
  •  1
  •   niyou    11 年前

    可以将变量作为参数传递

    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.
    }
    

    用法

    init($my_query_results);
    process($my_query_results);
    
        3
  •  -3
  •   Michał Fraś    11 年前

    或者您可以简单地执行全局变量:

    $my_query_results = null;
    function init() {
    
    $args = array(
        'post_type' => 'post'
    );
    $my_query_results = new WP_Query( $args );
    

    }

    推荐文章