Search code examples
phptwitter-oauth

Can't load Twitteroauth class from a separate file


Used very old TwitterOAuth library in my app for ages (worked fine) and decided to upgrade. Noticed that new version now contains autoload.php, which auto-loads many files (classes) from /src directory. Did everything according to instructions, but autoloader doesn't work. After searching the Internet and debugging app for 3+ hours, I found that TwitterOAuth works ONLY if I combine EVERYTHING (autoloader, functions etc.) into a single file. If I keep functions in functions.php, settings in settings.php, and so on, nothing works.

How do I solve it, so I can use TwitterOAuth with multiple files like with old version? For your convenience, I made a test file, so you can see the problem - http://www.lipskas.com/test.zip

Just download/launch it on your server/localhost. If you open index.php file, you will get 'Class 'TwitterOAuth' not found' error because all the code is split between 3 files (index.php, settings.php, functions.php).

Now open works.php and you will see everything works perfectly just because EXACTLY THE SAME CODE from 3 files is copied into a single file. What the hell?

Update: here's the code from works.php, this one works:

<?php
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

function do_something_with_twitter()
{
$connection = new TwitterOAuth("aaaa", "bbbb");
$content = $connection->get("account/verify_credentials");
print_r($content);
}

do_something_with_twitter();
?>

Here's the code from 3 separate files, it does NOT work:

index.php

<?php
require "settings.php";

do_something_with_twitter();
?>

settings.php

<?php
require "functions.php";
require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
?>

functions.php

<?php
function do_something_with_twitter()
{
$connection = new TwitterOAuth("aaaa", "bbbb");
$content = $connection->get("account/verify_credentials");
print_r($content);
}
?>

Solution

  • If someone has the same issue, you can fix it this way:

    Using new version of Twitteroauth library, you should include this line in EVERY file where Twitter library needs to be called (if your app has multiple files):

    use Abraham\TwitterOAuth\TwitterOAuth;