在 PHP 中的类中包含文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7056297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:54:12  来源:igfitidea点击:

Include a file in a class in PHP

phpclassvariablesinclude

提问by Jerodev

Is it possible to include a file with PHP variables inside a class? And what would be the best way so I can access the data inside the whole class?

是否可以在类中包含带有 PHP 变量的文件?什么是最好的方法,以便我可以访问整个班级内的数据?

I have been googling this for a while, but none of the examples worked.

我已经在谷歌上搜索了一段时间,但没有一个例子有效。

回答by Mihai Iorga

The best way is to load them, not to include them via an external file.

最好的方法是加载它们,而不是通过外部文件包含它们。

For example:

例如:

// config.php
$variableSet = array();
$variableSet['setting'] = 'value';
$variableSet['setting2'] = 'value2';

// Load config.php ...
include('config.php');
$myClass = new PHPClass($variableSet);

// In a class you can make a constructor
function __construct($variables){ // <- As this is autoloading, see http://php.net/__construct
    $this->vars = $variables;
}
// And you can access them in the class via $this->vars array

回答by Ernestas Stankevi?ius

Actually, you should append data to the variable.

实际上,您应该将数据附加到变量中。

<?php
    /*
        file.php

        $hello = array(
            'world'
        )
    */

    class SomeClass {
        var bla = array();
        function getData() {
            include('file.php');
            $this->bla = $hello;
        }

        function bye() {
            echo $this->bla[0]; // Will print 'world'
        }
    }
?>

回答by Eugene Manuilov

From a performance point of view, it would be better if you will use a .ini file to store your settings.

从性能的角度来看,最好使用 .ini 文件来存储您的设置。

[db]
dns      = 'mysql:host=localhost.....'
user     = 'username'
password = 'password'

[my-other-settings]
key1 = value1
key2 = 'some other value'

And then in your class you can do something like this:

然后在你的课堂上你可以做这样的事情:

class myClass {
    private static $_settings = false;

    // This function will return a setting's value if setting exists,
    // otherwise default value also this function will load your
    // configuration file only once, when you try to get first value.
    public static function get($section, $key, $default = null) {
        if (self::$_settings === false) {
            self::$_settings = parse_ini_file('myconfig.ini', true);
        }
        foreach (self::$_settings[$group] as $_key => $_value) {
            if ($_key == $Key)
                return $_value;
        }
        return $default;
    }

    public function foo() {
        $dns = self::get('db', 'dns'); // Returns DNS setting from db
                                       // section of your configuration file
    }
}