在下面的代碼是Codeigniter get_instance方法的非常最小化版本。所以你的情況,你可以在一開始有地方這樣的代碼:
/** Basic Classes to load the logic and do the magic */
class mainInstance {
private static $instance;
public function __construct()
{
self::$instance =& $this;
}
public static function &get_instance()
{
return self::$instance;
}
}
function &get_instance()
{
return mainInstance::get_instance();
}
new mainInstance();
/** ----------------------------------------------- */
,然後你可以這樣創建全局類:
class customClass1 {
public $userName = '';
function myForm() {
return '<input type="text" value="'.$this->userName.'" />';
}
}
/** This is now loading globally */
$test = &get_instance();
//If you choose to actually create an object at this instance, you can call it globally later
$test->my_test = new customClass1();
$test->my_test->userName = "johnny";
/** The below code can be wherever in your project now (it is globally) */
$test2 = &get_instance();
echo $test2->my_test->myForm()."<br/>"; //This will print: <input type="text" value="johnny" />
echo $test2->my_test->userName; //This will printing: johnny
由於這是目前全球範圍內,你甚至可以創建自己的像這樣的功能:「用戶名」的
function mainFunction() {
$tmp = &get_instance();
return $tmp->my_test->userName;
}
echo mainFunction();
'從函數return'吧!? – deceze 2013-03-03 09:57:07
將你的用戶名傳給你的mainFunction($ username)? – MIIB 2013-03-03 09:57:43
如果你不打算將標記的參數傳遞給類函數,你可以用'常量'代替你的類的'全局變量' – tnanoba 2013-03-03 09:57:51