我想从课外得到变数。
实施例,
的config.php
$config['function'] = array('filter_validate','form');
Controller.php这样
class Controller{
public function __construct()
{
foreach ($config['function'] as $key => $function_class) {
$function_class = new $function_class();
}
}
}
但是,我无法在Controller中获得$ config ['function']变量。怎么办?
答案 0 :(得分:1)
解决方案#1(带参数):
class Controller {
public function __construct($config) {
foreach ($config['function'] as $key => $function_class) {
$function_class = new $function_class();
}
}
}
解决方案#2(global - 不推荐):
class Controller {
public function __construct() {
global $config;
foreach ($config['function'] as $key => $function_class) {
$function_class = new $function_class();
}
}
}
答案 1 :(得分:0)
You need to pass config to the constructor, like this:
class Controller{
public function __construct($config)
{
foreach ($config['function'] as $key => $function_class) {
$function_class = new $function_class();
}
}
}
$config['function'] = array('filter_validate','form');
$controller = new Controller($config);
答案 2 :(得分:0)
任何类外的函数都是全局的,可以从任何地方调用。与变量相同..只记得使用全局变量。
<?php
function abc() { }
$foo = 'bar';
class SomeClass {
public function tada(){
global $foo;
abc();
echo 'foo and '.$foo;
}
}
?>