定义类 this_重新定义$ this?

定义类 this

定义类 this

I was wondering - can you redefine the special variable $this when in a method of a class. It turns out that yes, you can.

我想知道-您可以在类方法中重新定义特殊变量$ this吗? 事实证明,可以。

Consider this class: < ?php class Some { function Some(){} function another(){ $this = 5; var_dump($this); } } ?> If you create an object and call the another() method, it will redefine $this and will make it an integer as opposed to an object. < ?php $s = new Some(); $s->another(); ?> This gives int(5)

考虑这个类:<?php class Some {function Some(){} function another(){$ this = 5; var_dump($ this); 如果创建一个对象并调用another()方法,它将重新定义$ this并使它成为一个与对象相反的整数。 <?php $ s = new Some(); $ s-> another(); ?>这给出了int(5)

If you dump the instance after the method call it will still return 5, so it's not just a temporary re-definition.

如果在方法调用之后转储实例,它将仍然返回5,因此它不仅仅是临时的重新定义。

Similarly, you can even destroy an object from within a method of the class, like < ?php class Some { function Some(){} function another(){ $this = null; } } $s = new Some(); $s->another(); var_dump($s); ?> This will output NULL.

同样,您甚至可以从类的方法中销毁对象,例如<?php class Some {function Some(){} function another(){$ this = null; $ s = new Some(); $ s-> another(); var_dump($ s); ?>这将输出NULL

Tell your friends about this post on Facebook and Twitter

FacebookTwitter上告诉您的朋友有关此帖子的信息

翻译自: https://www.phpied.com/redefine-this/

定义类 this