试图在多个类上使用变量

时间:2015-07-20 14:46:42

标签: php

目前,我正在通过我的MVC中的每个函数启动我的数据库连接,如下所示:

<?php

class System extends Controller
{

    public static function get($info = '')
    {
        try
        {
            if($info):
                 $database = DatabaseFactory::getFactory()->getConnection();
                 $get_info = $database->prepare("SELECT * FROM site"); //get all the info from the datbase
                 $result = $get_info->execute(array($info)); //run the query
                 $information = $result->fetch(); //fetch the information
                 return $information->$info; //return the info to use on other parts of the site
            else:
                throw new Exception("There was an error selecting site information");
            endif;

        }catch(Exception $e)
        {
            echo $e->getMessage();
        }
    }
}

?>

这意味着我需要使用

$database = DatabaseFactory::getFactory()->getConnection();

在每个功能中。现在我试图在我的控制器中启动数据库变量(我的控制器扩展所有类)所以我可以只做$ database-&gt;准备而不是在每个函数中启动它。这将是什么方式&gt;

我试过了

var $database = DatabaseFactory::getFactory()->getConnection();

public $database = DatabaseFactory::getFactory()->getConnection();

无济于事。

1 个答案:

答案 0 :(得分:2)

在初始化期间无法执行此操作,因为成员变量初始化必须是静态的,并且您正在尝试调用函数。来自the manual

  

这个声明可能包括初始化,但是这个   初始化必须是一个常量值 - 也就是说,它必须能够   在编译时进行评估,不得依赖于运行时   信息以便进行评估。

相反,请在constructor

中进行
class Controller {
    protected $database;
    function __construct() {
        $this->database = DatabaseFactory::getFactory()->getConnection();
    }
}