DEV Community

Cover image for Can $this be Used Outside Class? (PHP)
Shoaiyb Sysa
Shoaiyb Sysa

Posted on • Updated on

Can $this be Used Outside Class? (PHP)

Yes it's possible to use $this outside class, And at the same time it is not possible, But how?
It can be done by including the file that contains $this inside the class, Just like below.

Note:
It only works by including the file with $this inside the class, And it is highly not recommended.

Example:

class.php

<?php
class myClass {
  private $say = 'I didn\'t say anything!';
  public function say(string $text): void {
    $this->say = $text;
  }

  public function hear(): void {
    require __DIR__ . '/test.php';
    echo $this->say;
  }
}
$myClass = new myClass();
$myClass->hear();
?>
Enter fullscreen mode Exit fullscreen mode

test.php

<?php
$this->say('I Said Using $this Outside Class Is Possible, But Not A Best Practice!');
?>
Enter fullscreen mode Exit fullscreen mode

At the end, The answer is NO, You can't use $this outside class.
Because it is not a best practice and doing that will trigger an error.

Discussion (8)

Collapse
xwero profile image
david duymelinck • Edited on

The title is false, you can't use $this outside a class.

The code works because you include test.php in a class method. If you include that file in php code without a class you get an error.

Collapse
shoaiyb profile image
Info Comment hidden by post author - thread only accessible via permalink
Shoaiyb Sysa Author • Edited on

Yeah, and that's what I just write in the second line above ⬆️

Collapse
xwero profile image
david duymelinck

The code does not work outside of the class. You do;

$MyClass = new MyClass();
$MyClass->hear();
Enter fullscreen mode Exit fullscreen mode

So you are using the code in test.php as a part of the class.

This will not work;

<?php

require 'test.php';
Enter fullscreen mode Exit fullscreen mode

And that is what you stating with; Yes it's possible to use $this outside class with php

Collapse
leob profile image
leob

You're literally including those lines of code within the class, almost like you'd paste them in ... I don't want to burst your bubble, but this is not a hugely earth-shattering discovery. Kudos for the effort, though ;)

Collapse
andreidascalu profile image
Andrei Dascalu

Ok, so it's not possible to use $this outside a class

Collapse
palalet profile image
RadekHavelka

Why would you do such nonsense ...

Collapse
shoaiyb profile image
Info Comment hidden by post author - thread only accessible via permalink
Shoaiyb Sysa Author

What 😳?

Collapse
adamalicki profile image
Adam

This promotes such a bad practice and habit. I hope no serious PHP dev utilizes this hacky junk in their code.

Some comments have been hidden by the post's author - find out more