views:

669

answers:

4

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 {$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.

+1  A: 

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'
pygorex1
sorry it didn't work for me. I am not sure why. Please see my EDIT 1.
keisimone
Are you calling `$user->changeTitle()` before or after assigning the object to Smarty?
pygorex1
my apologies. i am currently trying to output the property of the object. let me put in another EDIT message
keisimone
A: 

http://www.smarty.net/manual/en/language.syntax.variables.php

Andrew
sorry it didn't work for me. I am not sure why. Please see my EDIT 1.
keisimone
A: 
$smarty->assign('user', $user);

in template

{$user->title}
Sinan
sorry it didn't work for me. I am not sure why. Please see my EDIT 1.
keisimone
A: 

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.

keisimone