如何从其他函数中获取价值 - PHP

时间:2017-08-23 14:06:26

标签: php oop

我以OOP的形式提供Google AnalyticsAPI代码,我已经创建了访问类,但是我无法访问每个函数返回的变量。例如:

我的initializeAnalytics ();课程中有access函数。

function initializeAnalytics(){

$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

$client = new Google_Client();
$client->setApplicationName("xxxxxx");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
// $client->setRedirectUri($this->_redirectURI);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$analytics = new Google_Service_Analytics($client);

return $analytics;
}

我上课后AccessAnalytics ();

function acessaAnalytics(){
        global $results;
        $analytics = new access();
        $analytics->initializeAnalytics();
        $this->getFirstProfileId();
        $results = getResults($analytics, $profile);
        return $results;
    }

最后是班级getFirstProfileId ();

function getFirstProfileId($analytics) {

    $accounts = $analytics->management_accounts->listManagementAccounts();

    if (count($accounts->getItems()) > 0) {
        $items = $accounts->getItems();
        $firstAccountId = $items[0]->getId();

        // Get the list of properties for the authorized user.
        $properties = $analytics->management_webproperties
            ->listManagementWebproperties($firstAccountId);

        if (count($properties->getItems()) > 0) {
          $items = $properties->getItems();
          $firstPropertyId = $items[0]->getId();

          // Get the list of views (profiles) for the authorized user.
          $profiles = $analytics->management_profiles
              ->listManagementProfiles($firstAccountId, $firstPropertyId);

          if (count($profiles->getItems()) > 0) {
            $items = $profiles->getItems();

            // Return the first view (profile) ID.
            return $items[0]->getId();

          } else {
            throw new Exception('No views (profiles) found for this user.');
          }
        } else {
          throw new Exception('No properties found for this user.');
        }
      } else {
        throw new Exception('No accounts found for this user.');
      }

      return $items;
    }

问题是,如何在相互补充的功能之间获得这些值?提前谢谢!

1 个答案:

答案 0 :(得分:0)

1)将它们设置为全局变量,这样你只需通过调用它们就可以在每个函数中使用它们。

2)从函数中返回变量: return $ analytics; 并在调用该函数时分配它: $ NewVariable = initializeAnalytics();

这是我能想到的两个解决方案。