couldn’t find a similar topic but this may boil down to not knowing how to adresse my issue, so here goes.
I’ve got this block of code that’ll post to twitter using the epitwitter library:
<?php
include 'includes/EpiCurl.php';
include 'includes/EpiOAuth.php';
include 'includes/EpiTwitter.php';
include 'includes/tokens.php';
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($oauth_token, $oauth_secret);
$update_status = $twitterObj->post_statusesUpdate(array('status' => 'This is a test tweet!'));
$temp = $update_status->response;
?>
This is working perfectly and everything is good, until i do this:
<?php
include 'includes/EpiCurl.php';
include 'includes/EpiOAuth.php';
include 'includes/EpiTwitter.php';
include 'includes/tokens.php';
function postTweet() {
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$twitterObj->setToken($oauth_token, $oauth_secret);
$update_status = $twitterObj->post_statusesUpdate(array('status' => 'This is a sample tweet!'));
$temp = $update_status->response;
}
postTweet();
?>
Putting the code inside a function somehow breaks it and causes it to return a 500 error. Would anyone be able to explain this behavior and help me fix it?
Thanks in advance!
Most likely this is because all the secret and token variables are defined in global scope inside the included files. You moved them into a function out of scope, and one of the functions called inside it cannot handle the empty variables without erroring out.
Access them globally, or pass them as parameters to your function.
Recommended: Pass parameters to the function
Alternative: use
globalThe alternative solution, but the less preferred solution is to use the
globalkeyword (or$GLOBALS[]array). It is usually considered best practice to pass them as parameters as I’ve done above though.