Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set/replace $this variable in PHP

Tags:

php

class

this

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.

like image 603
David Rodrigues Avatar asked Feb 15 '26 08:02

David Rodrigues


1 Answers

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

like image 75
Stegrex Avatar answered Feb 16 '26 20:02

Stegrex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!