how to assign an object to smarty templates?
i created a model object in PHP
class User {
public $title;
public function changeTitle($newTitle){
$this->title = $newTitle;
}
}
How do i expose the property of a User object in smarty just by assigning the object?
I know i can do this
$smarty->assign('title', $user->title);
but my object has something like over 20 plus properties.
Please advise.
EDIT 1
the following didn't work for me.
$smarty->assign('user', $user);
OR
$smarty->register_object('user', $user);
then i try to {开发者_StackOverflow中文版$user->title}
nothing came out.
EDIT 2
I am only currently trying to output the public property of the object in the smarty template. Sorry if i confused any one with the function.
Thank you.
You should be able to access any public properties of an object from a Smarty template. For instance:
$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'
You can also use assign_by_ref
if you plan on updating the object after assigning it to the Smarty template:
class User2 {
public $title;
public function changeTitle($newTitle){
$this->title = $newTitle;
}
}
$user2= new User2();
$smarty->assign_by_ref('user2', $user2);
$user2->changeTitle('title #2');
And in the template file
{$user2->title} ## Outputs the string 'title #2'
$smarty->assign('user', $user);
in template
{$user->title}
This one works for me.
$smarty->register_object('user', $user);
// Inside the template. note the lack of a $ sign
{user->title}
This one doesn't work regardless whether i have the $ sign
$smarty->assign('user', $user);
I hope someone can tell me why.
精彩评论