从一个函数获取变量并在PHP中传递给另一个函数

时间:2015-06-11 15:18:58

标签: php

我在函数中有一个函数。函数B从API获取一个值并将其传递给函数A.但是,当我回显函数B中的值时,它可以工作,但在函数A中调用它时为null。

我应该在循环之间将值存储在会话变量或DB中吗?

function getFBLikes($postid) {

    //Get total number of likes per post
    $query = '/likes?summary=1&filter=stream';

    $request_likes = BASE_URL
    .$postid
    .$query
    .ACCESS_TOKEN;

    $result_likes = json_decode(file_get_contents($request_likes), true);

    foreach ($result_likes as $a => $b) {
        if(isset($b['total_count'])) {
            $likes = $b['total_count'];
            echo $likes /* THIS APPEARS AS A CORRECT VALUE */
        }
    }   
}

function getPostDetails($array){
    foreach ($array as $a => $b) {
        if(isset($b['type'])) {
            if(isset($b['object_id'])){
                $postid = $b['object_id'];
                $shares = $b['shares']['count'];
                $type = $b['type'];
                getFBLikes($postid);
                echo $likes; /* THIS IS NULL */
            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

添加

return $likes;

getFBLikes

getPostDetails

中使用它
$likes = getFBLikes($postid);

答案 1 :(得分:0)

function getFBLikes($postid) {

    //Get total number of likes per post        

    $query = '/likes?summary=1&filter=stream';

    $request_likes = BASE_URL
                     .$postid
                     .$query
                     .ACCESS_TOKEN;

    $result_likes = json_decode(file_get_contents($request_likes), true);

    foreach ($result_likes as $a => $b) {   

         if(isset($b['total_count'])){   
            $likes = $b['total_count'];
            //ADDED
            return $likes;
          }
     }   
}

function getPostDetails($array){

    foreach ($array as $a => $b) {

        if(isset($b['type'])) {

            if(isset($b['object_id'])){
                $postid = $b['object_id'];
                $shares = $b['shares']['count'];
                $type = $b['type'];

                //CHANGED
                $likes = getFBLikes($postid);

                echo $likes; /* THIS SHOULD NO LONGER BE NULL */
            }                                           
        }
    }               
}

应该做的伎俩。

你遇到的问题是getPostDetails是getFBLikes, 但getFBLikes并没有“回应”#39; (返回)任何东西给你带来了getPostDetails所以当你尝试回复喜欢的数量时它会变为null因为基本上它没有被告知有多少喜欢

答案 2 :(得分:0)

您需要getFBLikes() return一个值。

来自文档:

  

如果在函数内调用,则return语句会立即结束当前函数的执行,并将其参数作为函数调用的值返回。

示例解决方案: 在getFBLikes()添加:

echo $likes /* THIS APPEARS AS A CORRECT VALUE */
return $likes
<{>>在getPostDetails()中,您可以使用以下命令访问该值:

$likes = getFBLikes($postid); /* getFBLikes() will be return a value in $likes