Using Abraham's twitteroauth library inside of a function

php

#1

Hello! I’m quite new to namespaces and classes but I’m trying to implement @abraham’s twitteroauth library into my news website to post tweets when a new story is published. I’ve used his older library for some years now but I’ve updated in order to upload media. However, I am running into some issues and I think they stem from my lack of DEEP knowledge of PHP.

What I am trying to do is create a function called sendTweet() that accepts $text as a parameters so I can call it from multiple places on my site. On a basic test page, I can use the standard implementation provided in @Abraham’s docs to send out a tweet. Works perfectly. See below:

$consumerKey = MYKEY;
$consumerSecret = MYSECRET
.... etc.....

require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
	
// create a new instance
$connection = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
	
//send a tweet
$result = $connection->post('statuses/update', array('status' => $text));

However, if I do this (below), it does not work.

function sendTweet($content) {
  $consumerKey = MYKEY;
  $consumerSecret = MYSECRET
  .... etc.....

  require "twitteroauth/autoload.php";
  use Abraham\TwitterOAuth\TwitterOAuth;
	
  // create a new instance
  $connection = new TwitterOAuth($consumerKey, $consumerSecret, $oAuthToken, $oAuthSecret);
	
  //send a tweet
  $result = $connection->post('statuses/update', array('status' => $text));
}

$text = "The text contents of my tweet.";
sendTweet($text);

Is there something about the namespace and classes that’s preventing me from using this in a function? Any help would be greatly appreciated. Thank you!


#2

WOW… huge oversight on my part. I shouldn’t have included the require and use statements inside of the function. Moved them outside of the function and it works just fine.

Please ignore!


#3