0

I'm new to php. I'm trying to write a simple plugin that calls the api and returns a JSON response.

When I write the same code outside function, I get a JSON response. But the issue is when I use the function below, it doesn't return any value.. The page seems blank

Here is my function

function getDOTD(){
try{        
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $baseUrl."offers/v1/dotd/json");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Fk-Affiliate-Id:'.get_option('affiliate_id'),'Fk-Affiliate-Token:'.get_option('affiliate_token')));       
    $result = curl_exec($curl);
    curl_close($curl);
    print($result);

} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n"; abort;
}
}

i have also tried to use return instead of print() but that too didn't worked. this is how i call my function -

print(getDOTD());

Any help appreciated... TIA :)

5
  • 1
    Try changing print($result); to return $result; Commented May 11, 2016 at 19:16
  • i tried that too but it isn't working.. :( Commented May 11, 2016 at 19:18
  • Then I whould try to put die(); right after print($result); to see if it's actually getting any result. Also do var_dump($baseUrl); inside the function. Commented May 11, 2016 at 19:24
  • wow i did var_dump($baseUrl); inside function and it returned NULL.. how is that i am defining $baseurl above my function Commented May 11, 2016 at 19:28
  • Just use function getDOTD($baseUrl) instead. Commented May 11, 2016 at 19:47

1 Answer 1

1

You need to know how the variables scope works.

From the PHP Documentation

<?php
$a = 1; /* global scope */
function test(){
    echo 'local variable: ' . $a; /* reference to local scope variable // NULL */
}
test();
?>

To be able to access to the global scope you need to use the global keyword inside your function

<?php
$a = 'Hello World'; /* global scope */
function test(){
    global $a;
    echo 'global variable: ' . $a; /* reference to global scope variable // Hello World */
}
test();
?>

More info about the variables scope

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.