1

我使用自制的 MVC 系统,其中视图通过在方法的上下文中访问模型,因此能够访问$this.

动态包含的视图示例:

...
<div>
   Hello <?= $this->user->name ?>
</div>
...

现在,我有一些代码要分解为函数,并带有一些额外的参数。例如 :

function colored_hello($color) {
?>
<div style="background-color:<?= $color ?>">
   Hello <?= $this->user->name ?>
</div>
<?
}

问题是我无权访问$this,因为该函数不是方法。但我不想用演示文稿破坏我的模型或控制器。

Hance,我希望能够动态调用这个函数,作为一种方法。像面向方面的编程:

# In the top view
magic_method_caller("colored_hello", $this, "blue")

可能吗 ?或者你有没有更好的方法?

4

4 回答 4

3

Take a look at Closure::bindTo

You'll have to define/call your functions slightly differently, but you will be able to access $this from inside your object.

class test {
    private $property = 'hello!';
}

$obj = new test;

$closure = function() {
    print $this->property;
};

$closure = $closure->bindTo($obj, 'test');

$closure();
于 2012-07-26T15:08:00.283 回答
1

作为属性传递$this,但要严肃地说:您的视图文件中不应该有函数。

于 2012-07-26T15:18:40.987 回答
0

这有点骇人听闻,但您可以使用 debug_backtrace() 来获取调用者对象。但我认为你只能公开价值观:

function colored_hello($color) {
  $tmp=debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
  $last=array_pop($tmp);

  $caller = $last['object'];

  print_r($tmp);
  print_r($last);
  print_r($caller);

  ?>
  <div style="background-color:<?= $color ?>">
     Hello <?= $caller->user->name ?>
  </div>
  <?
}

(代码不是 testet,但它给了你一个提示:-))

于 2012-07-26T15:06:30.123 回答
-1

您也可以将其传递给函数:

function coloured_hello($object, $color) {
     //Code
     $object->user->name;
}
于 2012-07-26T15:19:58.367 回答