【问题标题】:PHP calling function within a class类中的 PHP 调用函数
【发布时间】:2016-02-21 01:55:34
【问题描述】:

我正在编写自己的 PHP 类,并且该类中有多个函数。像这样的:

class JSON_API_Hello_Controller {

public function test_cat(){
    global $json_api;

    $posts = $json_api->introspector->get_posts(array( 'cat' => 3));
    return $this->posts_object_result_bycat($posts);
}

public function test_cat1() {
    global $json_api;

    $posts = $json_api->introspector->get_posts(array( 'cat' => 2));
    return $this->posts_object_result_bycat($posts);
}

protected function posts_object_result_bycat($posts) {
    global $wp_query;

    return array(
        'count' => count($posts),
        'pages' => (int) $wp_query->max_num_pages,
        'posts' => $posts
    );
}

public function mix_cat(){

    $first_cat = $this->test_cat();
    $second_cat = $this->test_cat1();
   print_r($second_cat);

}

} 

我想在同一个类中的另一个函数中调用test_cat()test_cat1() 函数,例如mix_cat()。每次,它都会给出test_cat()test_cat1() 的结果为Null。如何调用mix_cat() 中的testcat()test_cat1() 函数?

【问题讨论】:

    标签: php json wordpress oop json-api


    【解决方案1】:

    调用函数的代码看起来不错 ($second_cat = $this->test_cat1(); print_r($second_cat);)。

    如果函数在从类外部调用时返回一个值,那么肯定有一些我们在这里看不到的外部变量。如果是这样,我们可能希望看到更多代码。

    附带说明一下,您可以通过传递 2、3 等参数来组合 test_cat() 和 test_cat1() 函数。它看起来像这样:

    public function test_cat1($number) {
        global $json_api;
        $posts = $json_api->introspector->get_posts(array('cat' => $number));
        return $this->posts_object_result_bycat($posts);
    }
    

    【讨论】:

    • 感谢您的回复,实际上,当我通过传递 2、3 等参数来尝试函数时,我在 mix_cat() 函数中调用了两个函数 [test_cat() 和 test_cat1()]。然后它只返回 test_cat() 函数的结果,不给出第二个函数 [test_cat1()] 的结果。它为 test_cat1() 函数提供空值。我试着像这样调用函数 $first_cat = $this->test_cat(2); $second_cat = $this->test_cat1(3); print_r($second_cat);
    • print_r($second_cat); value 没有显示 test_cat1() 函数数据的数据。每次它返回 test_cat() 函数的数据。请尝试帮助我。
    • 当我再次查看您的代码时,我认为您的代码是正确的并且可以正常工作。我认为问题出在数据上。有一种方法可以对此进行测试。如果切换“2”和“3”... test_cat() 返回 null 和 test_cat1() 是否成功?如果是这样,那么您的代码很好,问题出在数据上。
    猜你喜欢
    • 2013-06-19
    • 2012-09-26
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多