Kim*_*cks 1 php smarty variable-assignment viewmodel
我在PHP中创建了一个模型对象
class User {
public $title;
public function changeTitle($newTitle){
$this->title = $newTitle;
}
}
Run Code Online (Sandbox Code Playgroud)
如何通过分配对象来公开smarty中的User对象的属性?
我知道我能做到这一点
$smarty->assign('title', $user->title);
Run Code Online (Sandbox Code Playgroud)
但我的对象有超过20多个属性.
请指教.
编辑1
以下对我不起作用.
$smarty->assign('user', $user);
Run Code Online (Sandbox Code Playgroud)
要么
$smarty->register_object('user', $user);
Run Code Online (Sandbox Code Playgroud)
然后我试着 {$user->title}
一切都没有出来.
编辑2
我目前只想在smarty模板中输出对象的公共属性.对不起,如果我把任何一个与功能混淆.
谢谢.
您应该能够从Smarty模板访问对象的任何公共属性.例如:
$o2= new stdclass;
$o2->myvar= 'abc';
$smarty->assign('o2', $o2);
### later on, in a Smarty template file ###
{$o2->myvar} ### This will output the string 'abc'
Run Code Online (Sandbox Code Playgroud)
assign_by_ref如果您在将对象分配给Smarty模板后计划更新对象,也可以使用它:
class User2 {
public $title;
public function changeTitle($newTitle){
$this->title = $newTitle;
}
}
$user2= new User2();
$smarty->assign_by_ref('user2', $user2);
$user2->changeTitle('title #2');
Run Code Online (Sandbox Code Playgroud)
并在模板文件中
{$user2->title} ## Outputs the string 'title #2'
Run Code Online (Sandbox Code Playgroud)