PHP 将 $this 传递给类外的函数
你能像在 javascript 中一样传入 $this 变量以在“全局”空间中的函数中使用吗?我知道 $this 是用于课程的,但只是想知道。我试图避免使用“global”关键字。
例如:
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 是否可以完成同样的事情。
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.
For example:
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PHP 与 JavaScript 有很大不同。 JS 是一种基于原型的语言,而 PHP 是一种面向对象的语言。在 PHP 中,在类方法中注入不同的
$this
是没有意义的。您可能正在寻找将不同的
$this
注入到闭包(匿名函数)中。使用即将推出的 PHP 5.4 版本可以实现这一点。请参阅对象扩展 RFC。(顺便说一句,您确实可以将
$this
注入到不是instanceof self
的类中。但正如我已经说过的,这根本没有任何意义。 )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.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.(By the way you can indeed inject a
$this
into a class which is notinstanceof self
. But as I already said, this doesn't make no sense at all.)通常,您只需将其作为引用传递:
这会破坏私有变量和受保护变量的目的,即能够从代码外部访问 obj 的“$this”。 “$this”、“self”和“parent”是它们所使用的特定对象专用的关键字。
Normally, you would just pass it as a reference:
It would kind of defeat the purpose of private and protected vars, to be able to access "$this" of an obj from outside of the code. "$this", "self", and "parent" are keywords exclusive to specific objects that they're being used in.