PHP include doesn't work for TwitterOAuth.php,

2019-09-01 16:08发布

问题:

I am running into problems trying to include TwitterOAuth.php from https://github.com/abraham/twitteroauth to use the Twitter API.

My problem is this: I have a file called twitter.php in the same directory as my TwitterOAuth.php and OAuth.php files. When I try to use this snippet of code to connect:

include("TwitterOAuth.php");

//I actually fill in these values in my code, no worries...
$apikey = //"...";
$apisecret = //"...";
$accesstoken = //"...";
$accesssecret = //"...";

$connection = new TwitterOAuth($apikey, $apisecret, $accesstoken, $accesssecret);
print_r($connection);

I get this error (line 239 is the $connection=new TwitterOAuth(...) line):

Fatal error: Class 'TwitterOAuth' not found in /home/sites/(mydomain)/public_html/twitteroauth-master/src/twitter.php on line 239

However, if I copy and paste the entire contents of the TwitterOAuth.php file, replacing the line at which I call include("TwitterOAuth.php"); with those contents, everything works fine. I've also tried using include_once, require, and require_once, to no avail.

Please advise - I am very new to PHP and have no idea why copying and pasting works when include() doesn't.

Thanks!

回答1:

You should modify:

include("TwitterOAuth.php");

into:

include 'TwitterOAuth.php';
use Abraham\TwitterOAuth\TwitterOAuth;

to be able to access the TwitterOAuth in its defined namespace.

It is recommended to use include '<file>' because include is a special language construct, not a function, and should not be confused with a function.



回答2:

Are your files in the same directory? Since you are using include("TwitterOAuth.php"); then that means the files exist under the same directory. If it were include("../TwitterOAuth.php"); Then the file would exist in the parent directory