Skip to content Skip to sidebar Skip to footer

PHP Pass In $this To Function Outside Class

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

Solution 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.)


Solution 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.


Post a Comment for "PHP Pass In $this To Function Outside Class"