douji9184 2016-04-28 05:34
浏览 180
已采纳

如何在PHP中输出对象内的变量

I'm trying to use a variable from inside an object in PHP.

I've tried to access the variable like $object->json_output but I'm receiving undefined property errors. I'm expecting to regex this output and extract data which I'll use later on.

My code is:

class curl
  {
     public function curlPut($url, $JSON, $token)
     {
        $ch = curl_init($url);
        $popt = array(
           CURLOPT_CUSTOMREQUEST => 'PUT',
           CURLOPT_RETURNTRANSFER => TRUE,
           CURLOPT_SSL_VERIFYPEER => false,
           CURLOPT_POSTFIELDS => $JSON,
           CURLOPT_HTTPHEADER => array(
              'Content-Type: application/json',
              'Authorization:'.$token.''
           ));
        curl_setopt_array($ch, $popt);
        $json_output = curl_exec($ch);
        curl_close($ch);
        return var_dump($json_output);
     }
  };

$object1 = new curl;

$object1->curlPut($url, $JSON, $token);

preg_match_all('/"id":"([0-9]*)/', $object1->json_output, $idtest);
$id_array[] = array(
  'id' => $idtest[1]
);

where $json_output is the variable I need to access and $id_array is an array of IDs I need regexed from $json_output. How would I access $json_output to be used in my preg_match_all function?

I'm new to using class/objects so apologies if this is a silly question.

Any comments would be greatly appreciated!

Sam

展开全部

  • 写回答

2条回答 默认 最新

  • dsfsdfsdfsdf6455 2016-04-28 05:39
    关注

    You have to set a property on your class like the following:

    class Test {
      public $json_output = 'Test';
    }
    
    $test = new Test();
    echo $test->json_output; // output: Test;
    

    The property have to be public not private or protected to access outside the class.


    Your Code should look like the following:

    class curl {
      public $json_output = '';
    
      public function curlPut($url, $JSON, $token) {
        $ch = curl_init($url);
        $popt = array(
          CURLOPT_CUSTOMREQUEST => 'PUT',
          CURLOPT_RETURNTRANSFER => TRUE,
          CURLOPT_SSL_VERIFYPEER => false,
          CURLOPT_POSTFIELDS => $JSON,
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Authorization:'.$token.''
          ));
        curl_setopt_array($ch, $popt);
        $this->json_output = curl_exec($ch);
        curl_close($ch);
      }
    }
    
    
    $object1 = new curl();
    $object1->curlPut($url, $JSON, $token);
    
    preg_match_all('/"id":"([0-9]*)/', $object1->json_output, $idtest);       
    $id_array[] = array('id' => $idtest[1]);
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部