PHP需要静态方法内的文件

时间:2015-07-23 21:59:21

标签: php class methods include require

在我的课堂上,我有一个方法,包括基于输入的不同文件。

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

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

包含的文件:

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

班级方法:

/**
 * 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;
    }
}

希望有人可以帮助我

3 个答案:

答案 0 :(得分:1)

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

require_once $file;
return $cpucooler;

而不是

require $file;
return $cpucooler;

不知道为什么......

答案 1 :(得分:0)

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

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

失败的确切原因是猜测。也许路径不正确,因为你输错了,或者名字的情况是错误的,或者当前目录与你的想法不同。 (尝试使用绝对路径和/或使用__DIR__常量检查。

答案 2 :(得分:0)

确保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();
}