smarty php5.5,php5中Iterator与smarty整合
php5中Iterator與smarty整合
Iterator(迭代器)在PHP5中是非常重要的,我注意到Iterator在Smarty中不能正常的工作。
Smarty會自動將一個object(對象)轉換成array(數組),所以當年在Smarty中循環輸出一個object時,模板會自動循環這個object的屬性。
例如,建立一個類,然后在函數中定義某些要循環的部分,將這些部分放到protected類型的$_data變量中。
class MyClass implements Iterator
{
protected $_data = array();
public function rewind()
{
reset($this->_data);
}
public function current()
{
return current($this->_data);
}
public function key()
{
return key($this->_data);
}
public function next()
{
return next($this->_data);
}
public function valid()
{
return $this->current() !== false;
}
public function size()
{
return count($this->_data);
}
}
?>
然后在Smarty使用這個類
{foreach from=$myClassObj item=row}
{$row}
{/foreach}
這樣不會輸出想要的結果,下面做一下簡單的修改,將$myClassObj改成$myClassObj->getData():
{foreach from=$myClassObj->getData() item=row}
{$row}
{/foreach}
這樣就能輸出正確的結果了。
phpRiot.com: Using the PHP 5 Iterator interface with Smarty
The PHP 5 Iterator interface is very useful for defining custom behaviour for looping over objects, however I just noticed that looping over such objects in Smarty will not work correctly.
Smarty will in fact cast an object back to an array, so when you loop over it, the template will loop over the object''s properties (as opposed to using the rules defined by the Iterator methods).
For
總結
以上是生活随笔為你收集整理的smarty php5.5,php5中Iterator与smarty整合的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中channelmessage,
- 下一篇: php 文章搜索,登录 - 文章搜索 -