在PHP中设置/替换$ this变量

Dav*_*ues 2 php class this

有没有办法$this在PHP中设置或修改变量?在我的情况下,我需要调用一个匿名函数,其中$this引用的类不一定是进行调用的类.

示例:

function test() { 
    echo $this->name;
}

$user = new stdclass;
$user->name = "John Doe";

call_user_func(array($user, "test"));
Run Code Online (Sandbox Code Playgroud)

注意:这将生成错误,因为实际上,函数需要一个包含对象的数组和此对象中存在的方法,而不是任何全局范围的方法.

Ste*_*rex 6

为什么不尝试将函数定义设置为接受对象作为参数?例如:

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.
Run Code Online (Sandbox Code Playgroud)

变量$ this在类定义中使用时,指的是类的对象实例.在类定义之外(或在静态方法定义中),变量$ this没有特殊含义.当你试图在OOP模式之外使用$ this时,它会失去意义,并且依赖于OOP模式的call_user_func()将无法按照你尝试的方式工作.

如果您以非OOP方式使用函数(如全局函数),则该函数不依赖于任何类/对象,并且应以非OOP方式编写(传入数据或使用全局函数).


Ora*_*ill 5

您可以在闭包对象上使用bind方法来更改this特定上下文中的含义.请注意,此功能在PHP 5.4中可用.

官方说明

使用特定绑定对象和类范围复制闭包

  class TestClass {
       protected $var1 = "World";
  }
  $a = new TestClass();

  $func = function($a){ echo  $a." ".$this->var1; };
  $boundFunction = Closure::bind($func, $a, 'TestClass');

  $boundFunction("Hello");

  // outputs Hello World
Run Code Online (Sandbox Code Playgroud)

这种语法的替代方法是使用闭包实例的bindTo方法(匿名函数)

  class TestClass {
       protected $var1 = "World";
  }
  $a = new TestClass();

  $func = function($a){ echo  $a." ".$this->var1; };
  $boundFunction = $func->bindTo($a, $a);

  $boundFunction("Hello");

  // outputs Hello World
Run Code Online (Sandbox Code Playgroud)

在您的示例中,相关代码将是

$test = function() {
    echo $this->name;
};

$user = new stdclass;
$user->name = "John Doe";

$bound = $test->bindTo($user, $user);
call_user_func($bound);
Run Code Online (Sandbox Code Playgroud)

  • 别忘了提到它是`PHP 5.4 +`. (4认同)