2012-10-15 25 views
2

有序阵列我有以下的PHP类,它包含很多其他的应用程序为中心的功能my_new_iterative_function()旁边,但是当我进入foreach$this(我需要)范围变因上下文无效。通过$this以使其在method_foomethod_bar内有效的正确方法是什么?

注意:这是一个更为复杂的问题的一部分,并且所述$fallback_order在缺省顺序执行功能,但是my_new_iterative_function()需要接受的阵列,以控制的执行顺序(它是$order_functions阵列的目的

class Foo { 
    public function my_new_iterative_function(array $fallback_order = array('method_foo', 'method_bar')) { 

     $order_functions = array(
      'method_foo' => function(){ 
       // need to access $this 
      }, 
      'method_bar' => function(){ 
       // need to access $this 
      }, 
     ); 

     foreach ($fallback_order as $index => $this_fallback) { 
      $order_functions[$this_fallback](); 
     } 
    } 
} 
$instance_of_foo->my_new_iterative_function(); 
$instance_of_foo->my_new_iterative_function([ 'method_bar', 'method_foo', ]); 
+1

不能测试这个,因为我在工作,而且我们没有支持这个的PHP版本,但尝试将函数定义为''method_foo'=> function()use($ this){' – Izkata

回答

1

最简单的答案是,在通过$this作为参数:

$order_functions[$this_fallback]($this);

然后,你将需要:

$order_functions = array(
      'method_foo' => function($myObj){ 
       // use $myObj $this 
      }, 
      'method_bar' => function($myObj){ 
       // user $myObj instead of $this 
      }, 
     ); 

不管你做什么,你居然不能使用$this内像你这样的函数在类实例内,因为它们不是类实例的一部分。因此,您需要确保您具有某种类型的公共访问器,以便在这些函数中使用实例中需要使用的所有属性或函数。

+0

我必须接受这个答案,因为你正确地预料到了这个问题 - 我需要访问'Foo'类的其他非公共属性,这就是我需要处理这个问题的原因完全不同。 – Brian

3

你不能在这些函数中有$this,因为它们不属于foo类,它们只是foo类调用的匿名函数,如果你需要从匿名函数中访问类的成员,你应该只需通过$this即可:

$order_functions = array(
     'method_foo' => function($obj){ 
      // need to access $this using $obj instead 
     }, 
     'method_bar' => function($obj){ 
      // need to access $this using $obj instead 
     }, 
    ); 

    foreach ($fallback_order as $index => $this_fallback) { 
     $order_functions[$this_fallback]($this); 
    } 
+0

真的没有办法像'$ that = $ this;'这样做吗? '$ this'在'$ order_functions'之前和之后都有效当然有办法将它传递给方法数组...... – Brian

+0

当您将'$ this'传递给方法时,您将它称为'$ order_functions [$ this_fallback]($ this);' –

0

我看到的唯一方法是通过$this的职能

$order_functions = array(
    'method_foo' => function(Foo $foo){ 
     $foo->somePublicFunction(); 
    }, 
); 

$order_functions[$this_fallback]($this); 

但你只能调用公共职能上的Foo实例...如果符合您需求说不上来。