12
A
回答
13
最好的办法就是加载它们,不包括他们通过外部文件
如:
// config.php
$variableSet = array();
$variableSet['setting'] = 'value';
$variableSet['setting2'] = 'value2';
// load config.php ...
include('config.php');
$myClass = new PHPClass($variableSet);
// in 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
1
其实,你应该将数据追加到变量。
<?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'
}
}
?>
1
从性能的角度来看,这将是更好,如果你会使用.ini文件来存储您的设置。
[db]
dns = 'mysql:host=localhost.....'
user = 'username'
password = 'password'
[my-other-settings]
key1 = value1
key2 = 'some other value'
然后在你的类,你可以做这样的事情:
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 config 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 config file
}
}
相关问题
- 1. PHP类和包含文件
- 2. 包含文件到PHP类
- 3. 包含PHP中的文件
- 4. 包含包含另一个php文件的php文件?
- 5. PHP文件包含
- 6. PHP:包含文件
- 7. 仅包含一个PHP类文件
- 8. 包含HTML文件的PHP
- 9. PHP的index.php包含文件
- 10. PHP包含的XML文件
- 11. PHP类范围:类没有见过的包含文件中
- 12. 函数文件中不能包含类文件PHP
- 13. 如何从上述文件夹中包含PHP类文件
- 14. PHP使用另一个包含文件中的包含文件中的对象
- 15. 如何在PHP中包含已包含的文件中的文件?
- 16. PHP包含文件的下载文件
- 17. PHP包含动态url中的文件
- 18. 包含PHP文件中的Javascript
- 19. 包含文件中的PHP函数
- 20. PHP:包含文件中的“使用”?
- 21. 包含Java文件,如PHP的包括
- 22. 恒集包含PHP文件
- 23. PHP变量:包含文件?
- 24. 包含文件内容php
- 25. PHP文件包含错误
- 26. php jQuery包含文件
- 27. 包含外部PHP文件
- 28. php包含/名义文件?
- 29. PHP文件包含问题
- 30. PHP文件包含错误
你能多一些扩大你想做什么? –
请指出为什么没有http://stackoverflow.com/search?q=include+file+in+class+php回答你的问题。 – Gordon
这样做似乎是不可能的,所以我将使用xml来加载外部数据。 – Jerodev