0

I am tying to do following

class abc{

   public function abc(){

      someFunction(){
          now here I can not call bcg function like due to scope of function 
          function bcg(){
               $this->bcg();
         }

      }

   }

   public function bcg(){
     ...
   }
}

Now my question is how to pass object of current class to function which in method of class ?

2 Answers 2

2

You can pass through your current object into an anonymous function / closure by passing it into it as an argument:

// In an object method
$yourFunc = function ($object){
   $object->bcg();
}
$yourFunc($this);

If your function is defined outside of your class, you may also use this as a solution:

function myFunction($object) {
    $object->bcg();
}

class Foo {
    public function bgc() {
        // ...
    }
    public function doSomething() {
        myFunction($this);
    }
}

Note that your bcg function will be accessed from the public scope, so protected or private functions will not work.

Sign up to request clarification or add additional context in comments.

1 Comment

Fatal error: Cannot use $this as lexical variable. (I'd remove the first one), the second one works.
1

You cannot make a function inside a class method.

This should work:

class abc {

    public function abc() {
        $this->bcg(); // You can all bcg() here now
    }
    public function bcg() {

    }
}

1 Comment

@kelunik Thanks for the info. I learnt something new today :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.