其实要处理数组,不一定要套 for 循环,有一些很好用的数组函数啊,比如:
```
$data = array(
'filed1' => array(1, 2, 3),
'filed2' => array('a', 'b', 'c'),
'filed3' => array('x', 'y', 'z'),
);
$result = array_map(function ($filed1, $filed2, $filed3) {
return "('{$filed1}','{$filed2}','{$filed3}')";
}, $data['filed1'], $data['filed2'], $data['filed3']);
echo implode(',',$result);
```
第一次回复,这种懒加载可以用闭包哦
class DB
{
private $binds = [];
private $instances = [];
public function __construct()
{
$this->bind('a', function ($config) {
return new A($config);
});
$this->bind('b', function ($config) {
return new B($config);
});
}
private function bind($key, Closure $closure)
{
if (!isset($this->binds[$key])) {
$this->binds[$key] = $closure;
}
}
public function make($key, array $params)
{
if (isset($this->instances[$key])) {
return $this->instances[$key];
}
if (!isset($this->binds[$key])) {
return false;
}
$this->instances[$key] = call_user_func_array($this->binds[$key], $params);
return $this->instances[$key];
}
}
class A
{
private $config;
public function __construct($config)
{
$this->config = $config;
}
public function foo()
{
echo "Class A:\n";
var_dump($this->config);
}
}
class B
{
private $config;
public function __construct($config)
{
$this->config = $config;
}
public function foo()
{
echo "Class B:\n";
var_dump($this->config);
}
}
$db = new DB();
$a = $db->make('a', ['config for a']);
$a->foo();
$b = $db->make('b', ['config for b']);
$b->foo();
这确实是单例+依赖注入的问题
DB 类一般是要做单例的,这里只是写个例子就直接 new 了,不对的话请指教