【问题标题】:class not found if included from extern如果从外部包含,则找不到类
【发布时间】:2021-10-27 03:47:30
【问题描述】:

我有一个这样的文件夹结构:

+ inc
++ functions.php
++ vendor

+ private
++ carddav
+++ check.php

我的 check.php 看起来像这样并且可以工作:

<?php

require '../../inc/functions.php';

// CardDAV API
require '../../inc/vendor/autoload.php';

use MStilkerich\CardDavClient\{Account, AddressbookCollection, Config};
use Psr\Log\{AbstractLogger, NullLogger, LogLevel};
use Sabre\VObject\Component\VCard;
                    
class StdoutLogger extends AbstractLogger {
    public function log($level, $message, array $context = array()) {
        if ($level !== LogLevel::DEBUG) {
            $ctx = empty($context) ? "" : json_encode($context);
            echo ">>> ".$message . $ctx . "<br />";
        }
    }
}

Config::init(new StdoutLogger());
$account = new Account(URL, USERNAME, PASSWORD);
$abook = new AddressbookCollection(URL, $account);

$vcard =  new VCard();


?>

但是现在我想把这部分外包到我的functions.php中:

functions.php

<?

    // CardDAV API
    require 'vendor/autoload.php';
    
    use MStilkerich\CardDavClient\{Account, AddressbookCollection, Config};
    use Psr\Log\{AbstractLogger, NullLogger, LogLevel};
    use Sabre\VObject\Component\VCard;
                        
    class StdoutLogger extends AbstractLogger {
        public function log($level, $message, array $context = array()) {
            if ($level !== LogLevel::DEBUG) {
                $ctx = empty($context) ? "" : json_encode($context);
                echo ">>> ".$message . $ctx . "<br />";
            }
        }
    }
    
    Config::init(new StdoutLogger());
    $account = new Account(URL, USERNAME, PASSWORD);
    $abook = new AddressbookCollection(URL, $account);
?>

check.php

<?php

require '../../inc/functions.php';
$vcard =  new VCard();

?>

但现在我打开 check.php 时出现此错误:

Fatal error: Uncaught Error: Class 'VCard' not found in check.php:26

我的错误在哪里? 坦克你!

【问题讨论】:

    标签: php class


    【解决方案1】:

    使用use 语句导入以每个文件为基础。 IE。类需要在使用它们的文件中导入。在您的情况下,从 functions.php 中删除 Sabre\VObject\Component\VCard import 并将其移至实际使用 VCard 类的 check.php

    【讨论】:

      猜你喜欢
      • 2016-06-08
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 2020-01-23
      • 2015-09-04
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多