PHP 传入 $this 来在类外运行

问题描述 投票:0回答:2

你能像在 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 完成同样的事情。

php this
2个回答
3
投票

PHP 与 JavaScript 有很大不同。 JS 是一种基于原型的语言,而 PHP 是一种面向对象的语言。在类方法中注入不同的

$this
在 PHP 中没有意义。

您可能正在寻找的是向闭包(匿名函数)注入不同的

$this
。使用即将推出的 PHP 5.4 版本可以实现这一点。请参阅对象扩展 RFC

(顺便说一句,你确实可以将

$this
注入到不是
instanceof self
的类中。但正如我已经说过的,这根本没有任何意义。)


0
投票

通常,您只需将其作为参考传递即可:

class Example{
  function __construct(){ }
  function test(){ echo 'something'; }
}

function outside(&$obj){ var_dump($obj); $obj->test(); }

$example = new Example();

call_user_func_array('outside', array(&$example));

这会破坏私有变量和受保护变量的目的,即能够从代码外部访问 obj 的“$this”。 “$this”、“self”和“parent”是它们所使用的特定对象专用的关键字。

© www.soinside.com 2019 - 2024. All rights reserved.