在自定义 class 中访问 CakePHP $this
Accessing CakePHP $this in a custom class
我在 /src/Utility/foo.php
中有自己的 class foo
只要我添加 use App\Utility\foo;
就可以在任何 CakePHP 脚本中访问它 - 到目前为止这有效。
将调用者实例的 $this
对象传递给 PHP 构造函数通常没有问题。
为了获得 $this
的准确实例名称,我在 class 的构造函数中使用 get_class($this)
.
检索了它
这个returnsAdminLTE\View\AdminLTEView
- 我用
$fooInstance = new foo($this);
实例化我的自定义 class。
- 我的 class 的构造函数如下所示:
public function __construct(AdminLTE\View\AdminLTEView $appThis)
使用上述语法会导致此错误:
Argument 1 passed to App\Utility\foo::__construct() must be an
instance of App\Utility\AdminLTE\View\AdminLTEView, instance of
AdminLTE\View\AdminLTEView given
当我没有在构造函数中设置 $this
类型时,我在尝试此命令时收到以下 CakePHP 错误消息:
$appThis->request->getAttribute('identity');
:
requestHelper could not be found.
好的,我误解了什么,我错过了什么,正确的语法是怎样的,这样我就可以在我的自定义 class 中使用调用者 class 的 $this
?
get_class()
returns 已解析的名称(解析发生在编译时),并且已解析的名称没有前导反斜杠,但是 unresolved 完全限定的名称始终以反斜杠开头:
\AdminLTE\View\AdminLTEView
https://php.net/manual/en/language.namespaces.rules.php
View::$request
是受保护的 属性,您不能访问超出视图 class' 的范围,您必须使用其 public getRequest()
方法代替:
$appThis->getRequest()->getAttribute('identity');
访问未定义的属性将导致视图的魔术助手加载器启动,因此您可以在 view/template 中执行 $this->Html
以触发相应助手的延迟加载名称,即 HtmlHelper
.
我在 /src/Utility/foo.php
中有自己的 class foo
只要我添加 use App\Utility\foo;
就可以在任何 CakePHP 脚本中访问它 - 到目前为止这有效。
将调用者实例的 $this
对象传递给 PHP 构造函数通常没有问题。
为了获得 $this
的准确实例名称,我在 class 的构造函数中使用 get_class($this)
.
检索了它
这个returnsAdminLTE\View\AdminLTEView
- 我用
$fooInstance = new foo($this);
实例化我的自定义 class。 - 我的 class 的构造函数如下所示:
public function __construct(AdminLTE\View\AdminLTEView $appThis)
使用上述语法会导致此错误:
Argument 1 passed to App\Utility\foo::__construct() must be an instance of App\Utility\AdminLTE\View\AdminLTEView, instance of AdminLTE\View\AdminLTEView given
当我没有在构造函数中设置 $this
类型时,我在尝试此命令时收到以下 CakePHP 错误消息:
$appThis->request->getAttribute('identity');
:
requestHelper could not be found.
好的,我误解了什么,我错过了什么,正确的语法是怎样的,这样我就可以在我的自定义 class 中使用调用者 class 的 $this
?
get_class()
returns 已解析的名称(解析发生在编译时),并且已解析的名称没有前导反斜杠,但是 unresolved 完全限定的名称始终以反斜杠开头:
\AdminLTE\View\AdminLTEView
https://php.net/manual/en/language.namespaces.rules.php
View::$request
是受保护的 属性,您不能访问超出视图 class' 的范围,您必须使用其 public getRequest()
方法代替:
$appThis->getRequest()->getAttribute('identity');
访问未定义的属性将导致视图的魔术助手加载器启动,因此您可以在 view/template 中执行 $this->Html
以触发相应助手的延迟加载名称,即 HtmlHelper
.