Elavarasan
Elavarasan

Reputation: 2669

How to use $this in outside of class?

Can we use $this outside of class. Please look at the example below,

<?php 

class Animal {

    public function whichClass() {
        echo "I am an Animal!";
    }

    public function sayClassName() {
        $this->whichClass();
    }
}

class Tiger extends Animal {

    public function whichClass() {
        echo "I am a Tiger!";
    }

    public function anotherClass() {
        echo "I am a another Tiger!";
    }

}

$tigerObj = new Tiger();

//Tiger::whichClass();

$this->anotherClass();

Here I have created new object $tigerObj = new Tiger(); after that I tried to use $this but it throwing error. So is that possible to use $this from outside of the class ? If no, $this refers to the current object. So why don't we use this ?

Upvotes: 0

Views: 1656

Answers (4)

SYSA
SYSA

Reputation: 3

Yes it's possible to use $this outside class with php 8.

Example: class.php

<?php
class MyClass {
  private $say = '';
  public function say(string $text) {
    $this->say = $text;
  }

  public function hear() {
    require __DIR__ . '/test.php';
    echo $this->say;
  }
}
$MyClass = new MyClass();
$MyClass->hear();
?>

test.php

<?php
$this->say('Using this Outside Class Is Possible');
?>

Upvotes: 0

Pankaj Prajapati
Pankaj Prajapati

Reputation: 96

Its not possible to use $this in this way, you can create object of that class and then extend the methods which you would like to call. See below ...

class Animal {

    public function whichClass() {
        echo "I am an Animal!";
    }

    public function sayClassName() {
        $this->whichClass();
    }
}

class Tiger extends Animal {

    public function whichClass() {
        echo "I am a Tiger!";
    }

    public function anotherClass() {
        echo "I am a another Tiger!";
    }

}

$tigerObj = new Tiger();

echo $tigerObj->anotherClass();

You will get result "I am a another Tiger!"

Upvotes: 1

matwr
matwr

Reputation: 1571

NO you can't use $this outside the scope of a class

example :

1    $this=new \DateTime();
2    echo $this->format('r');

generates the following error :

Fatal error: Cannot re-assign $this on line 2

Upvotes: 1

Benjamin Poignant
Benjamin Poignant

Reputation: 1064

$this is impossible to use outside class so you can make static method, and use like this Tiger::anotherClass. Link to doc

class Animal {

    public function whichClass() {
        echo "I am an Animal!";
    }

    public function sayClassName() {
        $this->whichClass();
    }
}

class Tiger extends Animal {

    public function whichClass() {
        echo "I am a Tiger!";
    }

    public static function anotherClass() {
        echo "I am a another Tiger!";
    }

}

$tigerObj = new Tiger();

//Tiger::whichClass();

Tiger::anotherClass();

Upvotes: 1

Related Questions