douji9184 2016-04-28 13: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 13: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条)

报告相同问题?

悬赏问题

  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图