如何将方法的结果存储在一个变量中,然后我可以在 PHP 中的类外部使用该变量


How to store the results of a method in a variable that I can then use outside the class in PHP?

page-bulletins.php中的结构:

$args = array(
    'post_type' => 'post',
    'posts_per_page' => 3,
    'paged' => $paged
);
 $query = new WP_Query($args); if( $query->have_posts() ) :
     while( $query->have_posts() ) : $query->the_post();
         <!-- some code -->
     endwhile;
     // call the function 'posts_per_page' in the class 'cn_pages' using the value defined with the 'posts_per_page' key in '$args' above
     cn_pages::posts_per_page($args['posts_per_page']);
     // then call this function
     pass_page_info();
 endif;

functions.php中的代码:

class cn_pages {
    function posts_per_page($postsperpage) {
        return $postsperpage;
    }
}

我在类cn_pages之外定义了另一个函数,它需要 posts_per_page 方法的结果来计算总页数。

如何将此方法的结果存储到可以在定义该方法的类之外访问的变量中?

你可能想做这样的事情:

class cn_pages {
    public static $postperpage = 0;
    function posts_per_page($postsperpage) {
        self::$postsperpage = $postsperpage;
        return $postsperpage;
    }
}

则接收cn_pages::posts_per_page()的结果是:

pass_page_info(cn_pages::$postsperpage);

您可以执行以下操作:

$cnpages = new cn_pages();
$cnpages->posts_per_page($args['posts_per_page']);

这应该返回函数的值。

<?php    
class cn_pages {
    protected $foo;
    function posts_per_page($postsperpage) {
        $this->foo = $postsperpage;
    }
    public function get_foo(){
        return $this->foo;
    }
}

// outside of class create an instance of the class and call the function get_foo()

function outside_of_class(){
    $bar = new cn_pages;
    $foobar = $bar->get_foo(); // here you stored the result of the method in a variable
}