1

I have a function inside a function and the inner function cannot find the outer class. I don't know why. I hope someone has an idea how I can solve this. I don't want to declare the inner function outside of the outer function.

class Foo {

    public $test = "test123";

    private function outerfunction(){

        function innerfunction(){

            echo $this->test;

        }

        innerfunction();

    }

}

if I call the inner function I get the error Using $this when not in object context.

3
  • So pass it in as an argument Commented Jun 20, 2018 at 19:50
  • i dont can use this as default parameter, and i dont want include this everytime in this function Commented Jun 20, 2018 at 19:51
  • You are less likely to use inner functions in classes. These would more likely be private or protected functions in the class itself. Commented Jun 20, 2018 at 19:56

3 Answers 3

3

just restructure it to an anonymous function:

$innerfunction = function () {
    echo $this->test;
}

$innerfunction();

The class context is then automatically bound to the function (see also http://php.net/manual/en/functions.anonymous.php) Be aware, that this only works for >= PHP 5.4

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

Comments

2

You have to declare it as a variable, or it will tell you that you aren't in an object context:

    $innerfunction = function() {

        echo $this->test;

    };
    call_user_func($innerfunction);

Alternatively, you can keep the function as you do, and pass it the object context since it's known at the call point:

    function innerfunction(/* Foo */ $obj) {

        echo $obj->test;

    };
    innerfunction($this);

Comments

1

The most glaring issue with this approach is that calling outerFunction() more than once will produce:

Fatal error: Cannot redeclare innerfunction()...

Another issue is that innerfunction() is declared in the global scope. If this is intentional then that is highly unconventional and you probably should not do that. Anyways, it allows for this:

class Foo {

    public $test = "test123";

    public function outerfunction(){

        function innerfunction(){
            //echo $this->test;
        }

        innerfunction();
    }
}

$a = new foo();

// innerfunction(); // NOPE!
$a->outerFunction();
innerfunction(); // YES

So, this is the logical way to declare innerfunction():

class Foo {

    public $test = "test123";

    public function outerfunction(){
        $this->innerfunction();
    }

    private function innerfunction(){
        echo $this->test;
    }
}

$a = new foo();

$a->outerFunction();

Comments

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.