Reputation: 1293
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
Upvotes: 0
Views: 156
Reputation: 43574
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]);
Upvotes: 2
Reputation: 7441
Like this. You create class variable and then you set it using $this->json_output
. After that, it is accessible via $object->json_output
.
class curl
{
public $json_output; //Added by tilz0R
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); //Edit by tilz0R $this-> added
curl_close($ch);
return var_dump($json_output);
}
};
Upvotes: 1