douguang9014
2017-04-24 10:04
浏览 39
已采纳

如何更改cakephp中常量的值?

I am trying to change the value of constant in cakephp 3.x using below code:

    public function switchApiKey(){
                **/*** changing value of already defined key***/
define('GOOGLE_API_KEY','AIzaSyCzFMBxvOXiHs8DdYoXDwsgcNxtyIhPUBk');**
                $this->loadModel('ApiKeys');
                $current_api_key=GOOGLE_API_KEY;
                $youtube_api_url = "https://www.googleapis.com/youtube/v3/search?key=AIzaSyB2Dolp4pbvHLwwKLl_mT8GWsByy1Hyijk";
                $youtube_api_url = $youtube_api_url."&regionCode=GB&type=video&maxResults=50&part=snippet&q=".urlencode($track->name.' Music Video Vevo');
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_URL,$youtube_api_url);
                $result=curl_exec($ch);
                $response = json_decode($result, true);
                if($response['error']['code']==403){
                    /** Make previous key inactive **/
                    $query = $this->YoutubeChannels->query();

                    $query->update()
                        ->set(['status' => 'pending'])
                        ->where(['api_key' => GOOGLE_API_KEY])
                        ->execute();
                    /** Retrieving fresh key from database **/
                    $new_key=$this->ApiKeys->find()->where(['ApiKeys.status'=>'active'])->first();
                    echo $new_key; die;
                    define(GOOGLE_API_KEY,$new_key->api_key);
                }       
            } 

But getting below error: enter image description here

Please assist to resolve this error:

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshao2967 2017-04-24 10:57
    已采纳

    You can use global variables instead like:

    var $myVariable;
    

    // to access this variable

    $this->$myVariable;
    
    已采纳该答案
    打赏 评论