Not sure if this should go here or on the WordPress bit, will post it there if it's off topic :)
I'm trying to call an API (PHP newbie) and I'm completely stuck on how to proceed?? This is what I have so far...
class MyClass {
private static $instance = null;
protected function __construct() {
}
private function __clone() {}
private function __wakeup() {}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new self;
}
return self::$instance;
}
//Make the request
private function fetch_data($body) {
// Do we have this information in our transients already?
$transient = get_transient( 'fetch_data' );
// Yep! Just return it and we're done.
if( ! empty( $transient ) ) {
// The function will return here every time after the first time it is run, until the transient expires.
return $transient;
// Nope! We gotta make a call.
} else {
$api_url = "https://someapi.co.uk/api";
$request = wp_safe_remote_get( $api_url );
$body = wp_remote_retrieve_body(wp_safe_remote_get( $request ));
// Save the API response so we only call every hour
set_transient('fetch_data', '$body', 900);
if( is_wp_error( $request ) ) {
echo 'Something went wrong!';
return false; // Bail early
}
else
{
$my_data = json_decode( $body, true );
}
return $my_data;
}
}
}
MyClass::getInstance();
Any help would be appreciated :)
On another page I include the file where the class is
include(locate_template(('modules/my-api-bridge.php'), false, false));
and use this
$my_data = MyClass::getInstance();
When I var dump I get this back
object(MyClass)#3894 (0) {
}
I try and use the variable like this
echo $my_data['Itinary'] ['ItineraryDetails'] ['Name']
I get this error message
FATAL ERROR: UNCAUGHT ERROR: CANNOT USE OBJECT OF TYPE MyClass AS ARRAY
I assumed that json_decode($body, true) would convert the JSON object to a PHP array?
So I try and access the object like this
echo $my_data->Itinary->ItineraryDetails->Name
I get this error message
Notice: Undefined property: MyClass::$Itinary in...
Notice: Trying to get property of non-object in...
Notice: Trying to get property of non-object in...
Something is obviously amiss and I can't see what? Again, if this is more suited to the WordPress site then I'll repost it there :)