【问题标题】:How to properly use class from one file in another file?如何在另一个文件中正确使用一个文件中的类?
【发布时间】:2017-01-14 19:24:58
【问题描述】:

我有一个包含以下代码的文件 DHMOFramework/lib/Core/Core.php:

<?php

namespace DHMOFramework\lib\Core\Core;

/**
 * Main DHMOFramework class
 */

$registeredCommands = [];

class Core
{

  function registerCommand($command) {
    global $registeredCommands;
    $registeredCommands[$command] = [];
  }

  function registerSubCommand($commandname, $subcommand, $args, $helpmsg) {
    global $registeredCommands;
    $structure = array('command' => $commandname, 'subcommand' => $subcommand, 'args' => $args, "helpmsg" => $helpmsg);
    array_push($registeredCommands[$commandname], $structure);
    echo $registeredCommands;
  }

}

我还有另一个文件 test.php 包含此代码:

<?php

require_once "DHMOFramework/lib/Core/Core.php";

$dhmo = new Core();

$dhmo->registerCommand("command");
$dhmo->registerSubCommand("command", "subcommand", ["arg1" => [true, string], "arg2" => [true, boolean]], "Usage: /command subcommand <arg1> <arg2>");

当我运行 test.php 文件时,我不断收到此错误:

Fatal error: Class 'Core' not found in /home/ubuntu/workspace/test.php on line 5

Call Stack:
    0.0001     232464   1. {main}() /home/ubuntu/workspace/test.php:0

我该如何解决这个问题?

【问题讨论】:

  • 请包含两个文件的绝对路径。即:/home/ubuntu/workspace/test.php 但是 DHMOFramework/lib/Core/Core.php 相对于您的工作区在哪里? (如果你只拥有整个东西就更好了,比如它可能位于 /home/ubuntu/workspace/DHMOFramework/lib/Core/Core.php ?)

标签: php class include


【解决方案1】:

使用完整的类名:

$dhmo = new DHMOFramework\lib\Core\Core\Core();

或者在使用类之前使用use 语句:

use DHMOFramework\lib\Core\Core\Core;
$dhmo = new Core();

查看Official PHP documentation中的命名空间

【讨论】:

  • 我只是尝试了use语句和完整的类名。两者都不起作用,我得到同样的错误。
  • 我错过了完全限定类名中的一个核心。编辑了答案。
猜你喜欢
  • 2013-12-10
  • 2020-02-12
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
相关资源
最近更新 更多