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

1
  • Comments are not for extended discussion; this conversation has been moved to chat. Commented Jan 23, 2020 at 0:52

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

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.