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 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)