未找到命名空间中的 PHP 类

时间:2021-05-03 13:08:13

标签: php

我尝试从 Person 命名空间创建 Person 类,所有这些都包含在自动加载器文件中。 运行程序时,我收到错误消息:

destination_folder_id = 'YTRCA18EE ...'
shared_files = drive.ListFile({'q':'sharedWithMe'}).GetList()
for file in shared_files:
    drive.auth.service.files().copy(fileId=file['id'],body={'parents':[{"kind":'drive#file',"id":destination_folder_id}], 'title':file['title']}).execute()

这是我的代码和结构: index.php

Fatal error: Uncaught Error: Class 'Person\Person' not found in /opt/lampp/htdocs/testproject/index.php:13 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/testproject/index.php on line 13

自动加载功能(应该可以正常工作):

<?php
    include 'includes/autoloader.inc.php'
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>testproject</title>
    </head>
    <body>
        <?php            
            $person1 = new Person\Person('Lucas', 'Fußball', 21);

            echo $person1->getPerson();
        ?>

    </body>
</html>

Person 类:

<?php
spl_autoload_register('myAutoLoader');

function myAutoLoader($className) {
    $path = "classes/";
    $extension = ".class.php";
    $fullPath = $path . $className . $extension;

    if (!file_exists($fullPath)){
        return false;
    }

    include_once $fullPath;
}

我的文件夹结构如下:

<?php
namespace Person;

class Person {
    private $name;
    private $hobby;
    private $age;

    public static $drinkingAge = 21;

    public function __construct($name, $hobby, $age) {
        $this->name = $name;
        $this->hobby = $hobby;
        $this->age = $age;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function getPerson() {
        return 'Name: ' . $this->name . '<br>Hobby: ' . $this->hobby . '<br>Alter: ' . $this->age;
    }

    public static function setDrinkingAge($newDA) {
        self::$drinkingAge = $newDA;
    }
}

0 个答案:

没有答案
相关问题