3

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:...

function b() is declared as public.

1 Answer 1

8

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.
Sign up to request clarification or add additional context in comments.

3 Comments

@user681982 - If you want, I can show you an example that solves your problems but it's definitely not the right way to go. Let me know.
I'll beter make it in the right way, but to have in a pocket new tricks is just great. If it's not too busy, could you show me this please?
Now I see why it's not recomended, in my case it's not only unrecomended but also sily. Thanks for sharing this. High five!

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.