php oop call method from inside the method from the same class -
i've got following issue
class class_name { function b() { // } function c() { function a() { // call function b(); } } } when call function usual: $this->b(); error: using $this when not in object context in c:...
function b() declared public
any thoughts?
i'll appreciate help
thanks
the function a() declared inside method c().
<?php class class_name { function b() { echo 'test'; } function c() { } function a() { $this->b(); } } $c = new class_name; $c->a(); // outputs "test" "echo 'test';" call above. example using function inside method (not recommended)
the reason why original code wasn't working because of scope of variables. $this available within instance of class. function a() not longer part of way solve problem pass instance variable class.
<?php class class_name { function b() { echo 'test'; } function c() { // function belongs inside method "c". accepts single parameter meant instance of "class_name". function a($that) { $that->b(); } // call "a" function , pass instance of "$this" reference. a(&$this); } } $c = new class_name; $c->c(); // outputs "test" "echo 'test';" call above.
Comments
Post a Comment