【问题标题】:PHP - Class not found, but is requiredPHP - 未找到类,但它是必需的
【发布时间】:2016-08-28 13:14:51
【问题描述】:

我正在使用 Abraham TwitterOAuth PHP SDK。我在index.php 的顶部包含了库(文件存在+我使用<?php)。

<?php
require 'inc/oauth/autoload.php';
var_dump(file_exists('inc/oauth/autoload.php')); //true
use Abraham\TwitterOAuth\TwitterOAuth;

下面,在 HTML 之间,我在 div 中包含了一个 .php 文件,如下所示:

<?php include('div.php'); ?>

在这个 div.php 文件中,我实例化了 TwitterOAuth 类,这会引发错误:

if (isset($_COOKIE['token']) && !empty($_COOKIE['token'])) {
        $token = objectToArray(json_decode($_COOKIE['token']));
        $connection = new TwitterOAuth(CONSUMER, SECRET, $token['oauth_token'], $token['oauth_token_secret']);

这会引发错误Class 'TwitterOAuth' not found

注意

在我将代码移至 div.php 之前,此功能已正常运行。但是我需要将它分开,因为将来我将使用 JQuery 刷新 div。

【问题讨论】:

    标签: php class twitter-oauth require


    【解决方案1】:

    该类使用 Abraham\TwitterOAuth 命名空间 - 因此您必须包含它们或使用 fqn(完全限定的类名)

        $connection = new \Abraham\TwitterOAuth\TwitterOAuth(CONSUMER, SECRET, $token['oauth_token'], $token['oauth_token_secret']);
    

    【讨论】:

    • 谢谢,已修复(将在大约 6 分钟内接受)。为什么包含的文件会忽略来自index.phpuse Abraham\TwitterOAuth\TwitterOAuth;?因为当div.php 的代码直接在index.php 中时,同样的代码可以工作。为什么它不适用于包含?
    • 因为用use 声明的类别名只在同一个文件中知道。
    • 啊,我在 php.net 上看到:Importing rules are per file basis, meaning included files will NOT inherit the parent file's importing rules.。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2021-12-01
    • 2021-01-29
    • 1970-01-01
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多