<?php
class di{
function set($name,$value)
{
$this->_set[$name] = $value;
if(is_string($value))
$this->_type[$name] = 's';
else if(is_object($value))
if(is_callable($value)) //匿名函數類型是對象而且能夠調用
$this->_type[$name] = 'f';
else
$this->_type[$name] = 'o';
else if(is_array($value))
$this->_type[$name] = 'a';
else
$this->_type[$name] = 'f';
}
function pt()
{
print_r($this->_set);
print_r($this->_type);
}
function get($name)
{
return $this->_set[$name];
}
}
class db{
function getDb(){
return 'mysql';
}
}
$di = new di();
$di->set('test',function(){
echo $a='hello';
});
$di->set('db',new db());
$di->pt();
$b = $di->get('test');
$b();
php 5.4新功能
class bar {}
function
foo(bar $foo) {
}
//參數必須是bar類的實例,不然報錯
function
foo(
array
$foo) {}
//參數必須是數組
function foo(callable $callback) {
$callback('good');
}
//foo("false"); //錯誤,由於false不是callable類型
foo("printf"); //正確
foo(function($a){echo 'niming:'.$a;}); //正確
class A{
static function show($a){
echo 'method'.$a;
}
}
foo(array("A", "show")); //正確