2012-07-26 37 views
1

我使用自制的MVC系统,其中Views通过在方法的上下文中访问模型,因此能够访问$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") 

这可能吗? 或者你看到更好的方法吗?

+1

通$以此为论据? – 2012-07-26 14:58:05

+0

为什么你不把这个作为一个参数?另外,请查看php手册中的'call_user_func'。 – Florian 2012-07-26 14:58:26

+0

*视图访问模型* - 哦我的... – 2012-07-26 15:01:22

回答

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但它给你一个提示:-))

3

看看Closure::bindTo

你必须定义/以不同的方式调用你的函数,但你可以从你的对象内部访问$this

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

$obj = new test; 

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

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

$closure(); 
1

$this作为一个属性,但在所有的严重性:你不应该真的有在视图文件的功能。

-1

你可以或者将它传递给函数:

function coloured_hello($object, $color) { 
    //Code 
    $object->user->name; 
} 
+0

或使用类型提示 - 因为它专用于此目的 – Yang 2012-07-26 15:27:38