PHP:$this->的缩写,便于开发人员表示法


PHP: $this->something abbreviation for easier developer notation

我正在用PHP编写某种应用程序,开发人员可以在其中编写自己的插件。至于现在,每个插件构造函数对象$project作为参数传递(当然是通过引用)。例如,新插件如下所示:

<?php
namespace Plugins;
class newPlugin {
    private $project;
    public function __construct('Project $project) {
        $this->project = $project;
    }
    public function Something() {
        echo $this->project->template->name();
    }
}
?>

我正在重写它,所以每个新插件都扩展了"标准"插件。在这种情况下,我可以制作一个标准构造函数,将传递的$project本地保存为 $this->project,开发人员要写的更少。但是,每个开发人员都必须记住,有类似$this>项目的东西......

例如:

<?php
namespace Plugins;
class newPlugin extends Plugin { // constructor is now in plugin class
    public function Something() {
        echo $this->project->template->name(); 
        // where should the developer know from that $this->project exists?
    }
}
?>

我可以以某种方式使符号更容易吗?缩写$this->project我虽然关于在父级中创建一个将返回$this->project的方法项目()。在这种情况下,只能使用project()->template->name();。但这是...根本不是我认为最好的。

我希望我的问题一切都清楚,如果没有,请在评论中提问。我搜索了可能的答案,但一无所获。

PHP"use"很棒,但仅适用于命名空间...

顺便说一句,$this->project available下还有很多很多其他变量,但开头$this->project总是相同的。例如:$this->project->template->name(); $this->project->router->url(); $this->project->page->title();等...这个命名标准是强加的,所以没有办法改变它。

但是,当您每次需要某个地方的简单变量时都必须编写$this->project时,这真的很烦人。

感谢您的帮助。

下面是

使用__get()重载的项目的草图简单版本:

<?php
class Template
{
  public function name()
  {
    return 'Template';
  }
}
class Project
{
  public $template;
  public function __construct(Template $template)
  {
    $this->template = $template;
  }
}
class Plugin
{
  public $project;
  public function __construct(Project $project)
  {
    $this->project = $project;
  }
  // here it is. It will be called, if $template property doesn't exist in this Plugin.
  public function __get($val)
  {
    return $this->project->$val;
  }
}
class newPlugin extends Plugin { // constructor is now in plugin class
    public function Something() {
        echo $this->template->name(); // using this we will call __get() method because $template property doesn't exist. It will be transformed to $this->project->template->name();
    }
}
$template = new Template();
$project = new Project($template);
$plugin = new newPlugin($project);
$plugin->Something();

输出:

Template