How to use $this in outside of class?

2019-01-29 10:18发布

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 ?

标签: php class object
3条回答
混吃等死
2楼-- · 2019-01-29 10:35

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

查看更多
可以哭但决不认输i
3楼-- · 2019-01-29 10:51

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!"

查看更多
相关推荐>>
4楼-- · 2019-01-29 10:52

$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();
查看更多
登录 后发表回答