PHP CLass静态&非静态的

时间:2016-05-24 17:57:24

标签: php class template-engine

我有一个像这样的课程

class View
{

// Parameter die an das template übergeben werden
protected static $params = Array();
// Parameter die vom Routing übergeben werden
public static $routeParams;
// haupttemplate
protected static $viewMainContent;
// view template
protected static $viewFileContent;
// view pfad
protected static $pathTpl;
// controller pfad
protected static $pathCtrl;

protected $login;



// ausgabe des templates
public static function get($view, $params = "", $master = "main"){

    $this->$login = new Login();

    self::$pathTpl = Config::get('SRVROOT') . '/views/';
    self::$pathCtrl = Config::get('SRVROOT') . '/controller/';
    self::$routeParams = $params;
    // prüfen ob main template oder custom

....................
....

另一个类是非静态类。 现在我想在静态类中加载非静态类。 我的View类我想使用Login类中的函数。

这是一个模板类,我在View类中有一个函数。 在这个函数中,我加载一个已定义的控制器(xxx.php),在这个文件中,我想使用所有类的存在。

protected static function get_controller($file){
    $ctrlFile = self::$pathCtrl . $file.'.php'; 
    !file_exists($ctrlFile) || require_once($ctrlFile);

}

在函数中包含的文件中我有这段代码。

if($login->user()){ echo "Hallo ich bin eingeloggt"; }

浏览器中的错误

  

致命错误:未捕获错误:在第25行的/home/vagrant/Cloud/60_Projekte/SeitenVorlage/lib/class.templating.php中不在对象上下文中时使用$ this

我该怎么做?

2 个答案:

答案 0 :(得分:0)

您应将 $ pathCtrl 和其他属性定义为受保护,因为私有会阻止访问该属性/扩展类中的字段。

另外,我不认为从非静态类扩展静态类是一种很好的做法(我可能是错的),认为它们用于不同的目的。

我将静态类用于服务和提供者,非静态用于对象。

此问题的更多参考:What is the difference between public, private, and protected?

答案 1 :(得分:0)

您不能在静态函数中使用this。相反,尝试在静态函数中创建一个新对象:

$object = new Login();
$object->login();
.........

或者您可以将$ login更改为静态,然后使用self

self::$login = new Login();