问题描述
您能否像在 javascript 中一样传入 $this 变量以在全局"空间中的函数中使用?我知道 $this 用于课程,但只是想知道.我试图避免使用全局"关键字.
Can you pass in a $this variable to use in a function in the "global" space like you can in javascript? I know $this is meant for classes, but just wondering. I'm trying to avoid using the "global" keyword.
例如:
class Example{
function __construct(){ }
function test(){ echo 'something'; }
}
function outside(){ var_dump($this); $this->test(); }
$example = new Example();
call_user_func($example, 'outside', array('of parameters')); //Where I'm passing in an object to be used as $this for the function
在 javascript 中,我可以使用 call
方法并分配一个 this
变量用于函数.只是好奇是否可以用 PHP 完成同样的事情.
In javascript I can use the call
method and assign a this
variable to be used for a function. Was just curious if the same sort of thing can be accomplished with PHP.
推荐答案
PHP 与 JavaScript 有很大不同.JS 是一种基于原型的语言,而 PHP 是一种面向对象的语言.在类方法中注入不同的 $this
在 PHP 中没有意义.
PHP is very much different from JavaScript. JS is a prototype based language whereas PHP is an object oriented one. Injecting a different $this
in a class method doesn't make sense in PHP.
您可能正在寻找的是将不同的 $this
注入到闭包(匿名函数)中.这将可以使用即将推出的 PHP 5.4 版实现.请参阅对象扩展 RFC.
What you may be looking for is injecting a different $this
into a closure (anonymous function). This will be possible using the upcoming PHP version 5.4. See the object extension RFC.
(顺便说一句,您确实可以将 $this
注入到不是 instanceof self
的类中.但正如我已经说过的,这没有任何意义完全没有.)
(By the way you can indeed inject a $this
into a class which is not instanceof self
. But as I already said, this doesn't make no sense at all.)
这篇关于PHP 传入 $this 以在类外运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!