如何设置全局安全类php

时间:2015-03-23 22:52:46

标签: php class global

我正在尝试从另一个类的函数中访问类中的公共方法 我有:

带主要功能的文件

class kernel(){

private $conn;

private function mysqlconnection(){

$conn = new Mysqlconnection(); //Setup connection


}
private function makequery($query){

$this->conn->do_query($query); //do mysql query

}

public function query($query){

//check rank
...
 return $this->makequery($query); //if true do it

}

}

应用功能模板文件

Class app{

function __construct($appname){
//Check that this app can get connection (try make query)

$kernel->query($appname); 

}    

    }

$kernel = new kernel ();

$app = new app($appname); //HOW to access another class from class?

我通过调用类到全局

来实现
$GLOBALS['kernel'] = new kernel();

并在app类中 ...

    Class app{

function __construct($appname){
//Check that this app can get connection (try make query)

$GLOBALS['kernel']->query($appname); 

}    

    }

但我可以做得更安全吗?

2 个答案:

答案 0 :(得分:1)

通过构造函数

注入kernal的实例
Class app{

    protected $kernal;

    function __construct($appname, $kernal)
    {
        $this->kernal = $kernal //if needed in other methods, save to a property
        $this->kernal->query($appname); 
    }    
}


$kernel = new kernel ();

$app = new app($appname, $kernal);

答案 1 :(得分:0)

我是通过参考函数来做到的。 前

function ClassName(){
if(!isset($GLOBALS["ClassName"]))
$GLOBALS["ClassName"] = new $GLOBALS["ClassName"];

return $GLOBALS["ClassName"];
}

你可以通过

来调用它
ClassName()->query("...");

来自任何地方! :d