调用匿名函数来封闭$ this

问题描述

|| 我正在使用PHP 5.3匿名函数,并尝试模拟基于原型的对象,例如javascript:
$obj = PrototypeObject::create();

$obj->word = \"World\";

$obj->prototype(array(
    \'say\' => function ($ins) {
       echo \"Hello {$ins->word}\\n\";
    }
));

$obj->say();
这放\“ Hello World \”,第一个参数是该类的实例(如python),但是当我调用函数时,我想使用this变量:
$params = array_merge(array($this),$params);
call_user_func_array($this->_members[$order],$params);
尝试一下,没有结果:
call_user_func_array($this->_members[$order] use ($this),$params);
尝试使用__set方法:
$this->_members[$var] use ($this) = $val;
$this->_members[$var] = $val use ($this);
有任何想法吗?     

解决方法

        创建匿名函数时,父级的作用域由ѭ5继承。因此,您尝试执行的操作是不可能的。
$d = \'bar\';

$a = function($b,$c) use ($d)
{
  echo $d; // same $d as in the parent\'s scope
} 
也许更像这样的是您想要的:
$obj->prototype(array(
    \'say\' => function () use ($obj) {
       echo \"Hello {$obj->word}\\n\";
    }
));
但是匿名函数不会成为该类的一部分,因此,即使您要通过
$obj
传递\“
$this
\”作为参数,它也将无法访问该对象的私有数据。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...