Set/replace $this variable in PHP
class, php, this
Solution
Why not try setting the function definition to accept an object as a parameter? For example:
function test($object) {
if (isset($object->name)) // Make sure that the name property you want to reference exists for the class definition of the object you're passing in.
echo $object->name;
}
}
$user = new stdclass;
$user->name = "John Doe";
test($user); // Simply pass the object into the function.
The variable $this, when used in a class definition, refers to the object instance of the class. Outside of a class definition (or in a static method definition), variable $this has no special meaning. When you attempt to use $this outside of the OOP pattern, it loses meaning and call_user_func(), which relies on the OOP pattern, will not work in the way that you've attempted.
If you're using functions in a non-OOP way (like global functions), the function is not tied to any class/object and should be written in a non-OOP way (passing in data or otherwise using globals).
Problem
Is there a way to set or modify the variable `$this` in PHP? In my case, I need to call an anonymous function where `$this` refers to a class that is not necessarily the class that made the call. Pseudo-example: ``` function test() { echo $this->name; } $user = new stdclass; $user->name = "John Doe"; call_user_func(array($user, "test")); ``` Note: this will generate an error, because, in fact, the function expects an array containing an object and a method that exists in this object, and not any method of global scope.