对象以其原始名称传入参数


object passed in parameter with its original names?

我想在模板中使用不同的对象。 在站点的不同部分创建不同的对象。

目前我的代码是

public function notify ($template, $info)
{
    ob_start();
    include $template; 
    $content = ob_get_clean();
    //... more further code
}

如您所见$info参数。 我不想在模板中使用$info,但我要使用$photo、$admin或任何传递给它的东西。

我像这样使用

// for feed
$user->notify('email_template_feed.php', $feed);
// for new photo - i would also like to use $user inside templates
$user->notify('email_template_photo.php', $photo); 

我该怎么做? 不能使用全局,因为内部函数和函数在站点的不同位置/部分被动态调用,这可以进一步扩展。

你不能。

解决方案 1

相反,您可以使用数组并提取其值:

public function notify ($__template, array $info)
{
    ob_start();
    extract($info);
    include $__template; 
    $content = ob_get_clean();
    //... more further code
}

例 1

如果您使用以下命令调用它:

$user->notify('email_template_feed.php', array('feed' => $feed));

在模板内部email_template_feed.php

...
<?=$feed?>
...

它将打印:

...
FEED
...

解决方案 2

您还可以将变量的名称作为第三个参数传递:

public function notify ($template, $info, $name)
{
    ob_start();
    $$name = $info;
    unset($info);
    include $template; 
    $content = ob_get_clean();
    //... more further code
}

例 2

然后你可以通过以下方式调用它:

$user->notify('email_template_feed.php', $feed, 'feed');