tags:

views:

71

answers:

3

Hi everyone,

What do I need to do to call $this->two() from inside my function innerOne? Is that possible with PHP OOP?

Here's the error I am recieving:

Fatal error: Using $this when not in object context

Here's how my code looks:

class myClass  {

    function one(){

        function innerOne() {
            // Some code
            $this->two($var1, $var2);
        }

        // Some code

        innerOne();

    }

    function two($var1, $var2) {
    // Does magic with passed variables
        return $var1 . $var2;
    }


}

Thanks a lot!

Solution:

$t = $this;

function innerOne() {
    global $t;
    $t->two($var1,$var2);
}
+1  A: 

Try this:

   function innerOne( $t ) {
        // Some code
        $t->two($var1, $var2);
   }

   innerOne( $this );
Jacob Relkin
Thanks man! I used your example and thought outside the box a bit and was able to solve it! Posted my solution in my original post if anyone wonders. Thanks a lot!
Industrial
@Industrial: Make sure to accept this answer too.
BoltClock
Absolutely, I couldn't accept it at the time i wrote the comment. "You'll have to wait 2 minutes before accepting this answer" is an awesome message to see - not everyday you get an answer so quickly. Bigups to Jacob!
Industrial
@Industrial thanks
Jacob Relkin
+1  A: 

This function is only defined within that scope. So you can not access it outside of said scope. There are tricks around it but not any I'm going to recommend.

Ólafur Waage
Not true. innerOne is a global function once it's defined.
Artefacto
+1  A: 

innerOne is actually a global function.

The fact you defined it inside a method does not matter, it's in global function table. See:

class myClass  {

    static function one(){

        function innerOne() {
            // Some code
            echo "buga!";
        }


    }
}

myClass::one();

innerOne();

gives "buga!". You have to call one() first so that the function is defined.

What you want is this:

class myClass  {

    function one($var1, $var2){
        return $this->innerOne($var1, $var2);
    }

    private function innerOne($var1, $var2) {
        return $this->two($var1, $var2);
    }

    function two($var1, $var2) {
    // Does magic with passed variables
        return $var1 . $var2;
    }


}

$var = new myClass();
echo $var->one("bu","ga");
Artefacto