php – 在对象上下文中运行的回调函数?
发布时间:2020-12-13 22:03:41 所属栏目:PHP教程 来源:网络整理
导读:我试图在运行时配置一个对象传递一个回调函数,如下所示: class myObject{ protected $property; protected $anotherProperty; public function configure($callback){ if(is_callable($callback)){ $callback(); } }}$myObject = new myObject(); //$myObje
我试图在运行时配置一个对象传递一个回调函数,如下所示:
class myObject{ protected $property; protected $anotherProperty; public function configure($callback){ if(is_callable($callback)){ $callback(); } } } $myObject = new myObject(); // $myObject->configure(function(){ $this->property = 'value'; $this->anotherProperty = 'anotherValue'; }); 当然我收到以下错误:
我的问题是,如果有一种方法可以在回调函数中使用$this来实现此行为,或者可能会获得更好模式的建议. PS:我更喜欢使用回调. 解决方法
从你的想法开始,你可以将$this作为参数传递给你的回调
但请注意,您的回调(未在您的类中声明)将无法访问受保护的属性/方法 – 这意味着您必须设置公共方法来访问它们. 你的课程看起来像这样: class myObject { protected $property; protected $anotherProperty; public function configure($callback){ if(is_callable($callback)){ // Pass $this as a parameter to the callback $callback($this); } } public function setProperty($a) { $this->property = $a; } public function setAnotherProperty($a) { $this->anotherProperty = $a; } } 并且你已经宣布回调,并使用它,如下所示: $myObject = new myObject(); // $myObject->configure(function($obj) { // You cannot access protected/private properties or methods // => You have to use setters / getters $obj->setProperty('value'); $obj->setAnotherProperty('anotherValue'); }); 紧接着之后调用以下代码行: var_dump($myObject); 输出这个: object(myObject)[1] protected 'property' => string 'value' (length=5) protected 'anotherProperty' => string 'anotherValue' (length=12) 这表明已经执行了回调,并且确实已经按预期设置了对象的属性. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |