PHP pass in $this to function outside class

别等时光非礼了梦想. 提交于 2019-12-12 01:48:42

问题


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.


回答1:


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 not instanceof self. But as I already said, this doesn't make no sense at all.)




回答2:


Normally, you would just pass it as a reference:

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

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.



来源:https://stackoverflow.com/questions/7774444/php-pass-in-this-to-function-outside-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!