在下面的代码是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