Reputation: 15
<?php
class TryClass
{
private $data;
public function __construct($data)
{
$this->data = $data;
}
public function closure(Closure $callback)
{
return $callback(function () {});
}
}
$try = new TryClass('polat');
$try->closure(function ($reference) {
print_r($reference);
// not work
// $reference->this->data
// $reference::this->data
// $reference::$this->data
// $reference->{'this'}->data
});
print_r() response;
Closure Object
(
[this] => TryClass Object
(
[data:TryClass:private] => polats
)
)
How to access TryClass Object in Closure Object or How to access Static in Closure Object? Please help thank you so much.
By sending a closure function inside a class, I also want to access $this of that class inside that function.
Upvotes: 0
Views: 100
Reputation: 55427
You are passing a function to your closure, is that what you really want? So that your closure invokes a function? Instead, I think you just want to pass $this
back to your closure to get to it:
class TryClass
{
public function closure(Closure $callback)
{
return $callback($this);
}
}
(new TryClass())
->closure(
function ($reference) {
print_r($reference);
}
);
Output is:
TryClass Object
(
)
Demo here: https://3v4l.org/7Efpr
What you can't do is get access to the private variables without going through reflection, that would break incapsulation.
Upvotes: 0