PHP 在静态方法中需要文件

PHP Require file inside Static Method

在我的 class 中,我有一个方法,它包含基于输入的不同文件。

正确包含文件 => var_dump 显示 "true"。

但是!!如果我想访问包含的变量,它告诉我,它没有定义....

包含的文件:

<?php
$cpucooler = array(
array(
    "Name" => "Boxed CPU Lüfter",
    "Sockel" => "Alle",
    "Leistung" => 20,
    "RPM" => 2000,
    "Preis" => 0
));
?>

Class方法:

/**
 * Get Hardware for classes
 * @param string $type Hardware type
 * @return array
 */
public static function getHardware($type) {
    switch ($type) {
        case 'cpucooler':
            require_once "hardware/cpucooler.php";
            var_dump($cpucooler); // undefined variable...
            return $cpucooler;
            break;
    }
}

希望有人能帮助我

当我无法包含该文件时出现该错误。 如果包括作品,我也得到了数据。

总之,由于无法打开文件不是致命错误(只是一个警告),您可能已禁用输出警告,所以您看不到它们。如果您 enable error reporting,您应该会看到警告。

失败的确切原因是猜测。可能路径不对,因为你打错了,或者名字大小写不对,或者当前目录和你想的不一样。 (尝试使用绝对路径 and/or 使用 __DIR__ 常量检查。

确保确实包含 hardware/cpucooler.php。最好使用 is_file 来确保您的 require 文件存在于您的应用程序中。

try {
    $filepath = 'hardware/cpucooler.php';
    if( ! is_file(  $filepath ) ) {
        throw new Exception( $filepath . ' do not exists.' );
    } 
    // If exception is thrown, the following code is not executed.
    require $filepath;
    return $cpucooler;
} catch( Exception $e ) {
    echo $e->getMessage();
}

文件已正确包含,问题是,我使用了

require_once $file;
return $cpucooler;

而不是

require $file;
return $cpucooler;

不知道为什么...