开发者

php oop call method from inside the method from the same class

I've got the following issue

class class_name {

function b() {
   // do something
}

function c() {

   function a() {
       // call function b();
   }

}

}

When I call function as usual: $this->b(); I get this error: Using $this when not in object context in C:...

functi开发者_C百科on b() is declared as public

any thoughts?

I'll appreciate any help

Thanks


The function a() is 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" from the "echo 'test';" call above.

Example using a function inside a method (not recommended)

The reason why your original code wasn't working is because of scope of variables. $this is only available within the instance of the class. The function a() is not longer part of it so the only way to solve the problem is to pass the instance as a variable to the class.

<?php

class class_name {
  function b() {
    echo 'test';
  }

  function c() {
    // This function belongs inside method "c". It accepts a single parameter which is meant to be an instance of "class_name".
    function a($that) {
      $that->b();
    }

    // Call the "a" function and pass an instance of "$this" by reference.
    a(&$this);
  }
}

$c = new class_name;
$c->c(); // Outputs "test" from the "echo 'test';" call above.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜