开发者

How to access function inside PHP OOP

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);
        }

        /开发者_如何学Python/ Some code

        innerOne();

    }

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


}


Try this:

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

innerOne($this);


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");


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜