在课外如何使用$ this? [英] How to use $this in outside of class?

查看:42
本文介绍了在课外如何使用$ this?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在课外使用 $ this 吗?请看下面的例子,

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();

在这里我创建了新对象 $ tigerObj = new Tiger(); 之后,我尝试使用 $ this ,但是它抛出错误。那么可以在课外使用 $ this 吗?如果否,则
$ this 引用当前对象。那么,为什么不使用它呢?

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 ?

推荐答案

不可能以这种方式使用$ this,您可以创建对象该类,然后扩展您要调用的方法。见下文...

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

这篇关于在课外如何使用$ this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆