是否可以在类中包含带有php变量的文件?那么如何才能最好地访问全班内的数据呢?
我已经谷歌搜索了一段时间,但没有一个例子有效。
谢谢你, Jerodev
答案 0 :(得分:14)
最好的方法是加载它们,而不是通过外部文件包含它们
例如:
// 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 :(得分: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'
}
}
&GT;
答案 2 :(得分: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
}
}