Peter VARGA
Peter VARGA

Reputation: 5186

Accessing CakePHP $this in a custom class

I have my own class foo in /src/Utility/foo.php which can be accessed in any CakePHP script as long I add use App\Utility\foo; - that far this works.

There is usually not a problem to pass to a PHP constructor the $this object of the caller instance.

In order to get the exactly instance name of $this I retrieved it in the constructor of my class using get_class($this).
This returns AdminLTE\View\AdminLTEView

Using the above syntax results in this error:

Argument 1 passed to App\Utility\foo::__construct() must be an instance of App\Utility\AdminLTE\View\AdminLTEView, instance of AdminLTE\View\AdminLTEView given

When I don't set in the constructor the type of $this I receive the below CakePHP error message trying this command:
$appThis->request->getAttribute('identity');:

requestHelper could not be found.

OK, what did I misunderstand, what am I missing, how is the correct syntax so I can use $this of the caller class in my custom class?

Upvotes: 0

Views: 100

Answers (1)

ndm
ndm

Reputation: 60463

get_class() returns an already resolved name (resolving happens at compile time), and resolved names have no leading backslash, unresolved fully qualified names however always start with a backslash:

\AdminLTE\View\AdminLTEView

https://php.net/manual/en/language.namespaces.rules.php

View::$request is a protected property, you cannot access is out of the view class' scope, you'll have to use its public getRequest() method instead:

$appThis->getRequest()->getAttribute('identity');

Accessing undefined properties will cause the view's magic helper loader to kick in, so that you can for example do $this->Html in your view/template in order to trigger lazy loading of the respective helper matching that name, ie HtmlHelper.

Upvotes: 1

Related Questions