 |
Smarty
The discussions here are for Smarty, a template engine for the PHP programming language. Dedicated server web hosting provided by Guru-host.eu. |
| View previous topic :: View next topic |
| Author |
Message |
fms Smarty Rookie
Joined: 30 Jun 2012 Posts: 6
|
Posted: Sat Jun 30, 2012 8:09 am Post subject: {$myClass->mySubClass()->mySubClassMethod()} |
|
|
How to cleanly acces that in a smarty template: $myClass->mySubClass()->mySubClassMethod().
An exemple:
=> My classes
| Code: | class color {
private $fgColor;
private $bgColor;
function __construct($fgColor=null,$bgColor=null) {
$this->fgColor=$fgColor;
$this->bgColor=$bgColor;
}
public function getFgColor() {
return $this->fgColor;
}
public function getBgColor() {
return $this->bgColor;
}
}
class document {
private $title;
private $color;
function __construct() {
$this->title=null;
$this->color=new color('black','white');
}
public function &getColor() {
return $this->color;
}
public function setTitle($title) {
// Some checkout / formating
return $this->title=$title;
}
public function getTitle() {
return $this->title;
}
} |
=> My Model
| Code: | $doc = new document();
$doc->setTitle('My new document!');
$smarty->assign_by_ref('doc', '$doc'); // or some other assignation method |
=> In my template
| Code: | Doc title : {$doc->getTitle()} <= No problem
Foreground color : {$doc->getColor()->getFgColor()} <= Does not work :cry:
{assign var=color value=$doc->getColor()}
Foreground color : {$color->getFgColor()} <= Working but dirty |
Someone can help / have the soluce? |
|
| Back to top |
|
rodneyrehm Administrator

Joined: 30 Mar 2007 Posts: 698 Location: Germany, border to Switzerland
|
Posted: Sat Jun 30, 2012 8:44 am Post subject: |
|
|
{$foo->bar()->baz()} does not work in Smarty2. Smarty3 understands this syntax.
you can explode the chaining:
| Code: | {assign var="bar" value=$foo->getBar()}
{$bar->baz()} |
Or you could add a __get() magic method to your objects.
| Code: | class Foo {
public function getBar() {
return "Hello World";
}
public function __get( $name )
{
$fn = 'get'. ucfirst($name);
if (is_callable(array($this, $fn))) {
return $this->$fn();
}
// possibly trigger error?
return null;
}
} |
that now allows you to invoke the getBar() method by accessing $foo->bar.
both options aren't the neatest. If you can, upgrade to Smarty3! _________________ Twitter |
|
| Back to top |
|
fms Smarty Rookie
Joined: 30 Jun 2012 Posts: 6
|
Posted: Sat Jun 30, 2012 8:55 am Post subject: |
|
|
Thank you very much for your reply!
So I will look for updating my smarty release
thx |
|
| Back to top |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|