I'm trying to create mailchimp class to be used later, however I have problems with __constructor function. Without constructor, by just using add($data, $list) its working fine, but with __constructor this just output (int)0, when it should be (int)200...
There is 2 lists to chose from, add, get and delete functions...
Curl works WITHOUT constructor, when I combine constructor to add function, everything works just fine, issue is with the constructor
Class file:
class mailchimp
{
private $apiKey = '<apiKey>';
private $list1 = 'listOneId';
private $list2 = 'listTwoId';
function __construct($data, $list)
{
$listId = $list === 'list1' ? $this->list1 : $this->list2;
$memberId = md5(strtolower($data['email']));
$dataCenter = substr($this->apiKey,strpos($this->apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
}
function add() {
$json = json_encode([
'email_address' => $data['email'],
'status' => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $this->apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpCode;
}
function get($email)
{
File where executed(add and get):
include_once 'mailchimp.class.php';
$data = array(
'email' => '[email protected]',
'status' => 'subscribed'
);
$mc = new mailchimp($data, 'list2');
var_dump($mc->add());
Or
$data = array(
'email' => '[email protected]'
);
$mc = new mailchimp($data, 'list1');
var_dump($mc->get());
$mc = new mailchimp($data, 'list2'); var_dump($mc->add());then constructor does not work, if I execute this without constructor and move constructor insides to function add itself, it works... Like I execute this withadd($data, $list2)without constructor, it works.