php - Using $this when not in object context with ReflectionFunction->invoke() -
class someclass { private $success = "success\n"; function getreflection() { homecoming new reflectionfunction(function() { print $this->success; }); } } $reflection = (new someclass)->getreflection(); $reflection->invoke();
when run this, a
fatal error: using $this when not in object context in command line code on line 5
what's happening here? why $this
not defined there...?
as i'm in closure within method, $this
should defined. , yes, i'm on newer version php 5.4.
how can prepare it?
reflectionfunction operating on unbound closures. that's why after reflectionfunction::invoke()
call, there's no defined $this
variable within closure , such fatal error appears.
but there's way around it.
reflectionfunction bids 3 necessary methods phone call $this
binding:
reflectionfunctionabstract::getclosure()
reflectionfunctionabstract::getclosurethis()
reflectionfunctionabstract::getclosurescopeclass()
the reflectionfunctionabstract::getclosure()
still unbound, can bind via closure::bind()
.
all closure::bind()
needs closure, wished object bound , class scope.
then solution is:
call_user_func(\closure::bind( $reflection->getclosure(), $reflection->getclosurethis(), $reflection->getclosurescopeclass()->name));
i wanted post question only, had found solution myself before posting, adding answer. context issue: https://github.com/rdlowrey/auryn/pull/72
php reflection this fatal-error
No comments:
Post a Comment