-2

I have a class with the following structure:

/**
 * @property int ticket_id
 */
class Test {
    public function __construct( $ticket_id ) {
        $this->ticket_id = $ticket_id;

        $this->register();
    }

    /**
     * Register all hooks
     */
    public function register(): void {
        add_action( 'wp_ajax_ping', array( $this, 'ping' ) );
    }

    public function ping(): void {
        require_once('ping.php');
    }
}

In my ping.php I've tried using my parameter $this->ticket_id but I got an error that $this is not available in non object context:

error_log($this->ticket_id);

And yes, I'm creating a new object from my class:

new Test('123');

Why? I thought I can use it inside any required file too.

Martin
  • 22,212
  • 11
  • 70
  • 132
Mr. Jo
  • 4,946
  • 6
  • 41
  • 100
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/206481/discussion-on-question-by-mr-jo-php-this-is-not-available-in-non-object-conte). – Samuel Liew Jan 23 '20 at 00:52

1 Answers1

1

Your problem:

Basically, when the interpreter hits an include 'foo.php'; statement, it opens the specified file, reads all its content, replaces the "include" bit with the code from the other file and continues with interpreting...

reference

This means that the included file is parsed by PHP before being "imported" and as it's not in a class context until it's imported, when it's read, so the $this is out of place.

Possible Work arounds:

1) Put the included details in the parent class (copy/paste)

2) Put the included details in their intended class method and use PHP Class Extension to use an Extension class.

3) Extract the info. in the include and place it in its own class entirely. Place the include call in the parent script rather than the test class script. Reference

(there's probably more ideas how to work around your issue, but the best by a loooong chalk is one - to simply copy and paste the code in. If the code is verbose then you can easily hide it with any decent IDE closing off that method to one line of visible code.)

(From the point of view of the PHP compiler you're not saving anything with includes.)

Martin
  • 22,212
  • 11
  • 70
  • 132