【问题标题】:PHP CLass static & non staticPHP CLass 静态和非静态
【发布时间】:2016-05-24 17:57:24
【问题描述】:

我有这样的课程

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

我该怎么做?

【问题讨论】:

    标签: php class template-engine


    【解决方案1】:

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

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

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

    self::$login = new Login();
    

    【讨论】:

    • 谢谢它很好用。我已经测试了你答案的第一个版本
    【解决方案2】:

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

    另外,我认为从非静态类扩展静态类不是一个好习惯(我可能错了),认为它们有不同的用途。

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

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

    【讨论】:

    • 我已经尝试过保护,但它不起作用。我已经更新了我的帖子。
    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多