【问题标题】:Smarty and OOP within a compiled tpl已编译 tpl 中的 Smarty 和 OOP
【发布时间】:2012-12-27 17:04:26
【问题描述】:
$_smarty_tpl->tpl_vars['Variable']->value

我想知道 smarty 是如何访问对象的。 smarty_tpl 是对象,但是编译的 tpl 的代码示例中的属性是什么?是数组tpl_vars 还是value 还是两者的混合?

在 php 中,我创建了一个 smarty 对象并将其与方法一起使用(例如分配和显示)。 在模板本身(文件 .tpl)中,我不使用 OOP,而是使用类似 html 的程序样式。

【问题讨论】:

  • 我找到了另一个例子:$_smarty_tpl->tpl_vars['SearchTop5']->value[$_smarty_tpl->getVariable('smarty')->value['section']['i'] ['index']]['Value'] 这里,三个箭头用来访问什么?在本例中,'value' 是一个数组,在第一个示例中,它是一个字符串?
  • 我不确定我是否理解,您是否试图从 PHP 中访问分配给 smarty 的变量?不是模板文件本身?你想达到什么目的?
  • 您好,感谢您事先就 isset 和通知提供的信息。我在这个关于 tpl_vars 的问题中的想法是理解聪明。我不想访问 php 中的 smarty 变量。我只是想知道 $_smarty_tpl->tpl_vars['Variable']->value 的声明是做什么的,因为我在 oop 中从未见过类似的东西。在我看来,属性和数组是混合的?
  • 这个语法,$_smarty_tpl->tpl_vars['Variable']->value,意思是$_smarty_tpl->tpl_vars['Variable']是一个对象,所以$_smarty_tpl->tpl_vars是一个数组对象,这是很常见的
  • 不,PHP 不支持这种语法。请参阅我的答案以获取示例

标签: arrays oop smarty


【解决方案1】:

我试着做了一个小例子,希望能让你明白这个语法:

//A class that represents a fruit basket, a collection of fruits. Similar to $smarty, which is a collection of variables (among other things)
class FruitBasket
{
    public $basket = array();

    public function foo() {

    }
}
//A class that represents a fruit. It has some properties, like 'name' and 'color' 
class Fruit
{
    public $name = null;
    public $color = null;

    public function __construct($fruit_name) {
        $this->name = $fruit_name;
    }
}

$fruits = array();  //Make an array that will hold various fruits

$fruit = new Fruit('banana');   //Create a fruit
$fruit->color = 'yellow';       //Assign a value to its 'color' property 
$fruits['banana'] = $fruit;     //Assign the fruit to the 'fruits' array

//Make the same steps for 2 more fruits
$fruit = new Fruit('apple');
$fruit->color = 'red';
$fruits['apple'] = $fruit;

$fruit = new Fruit('pear');
$fruit->color = 'green';
$fruits['pear'] = $fruit;

$fruit_basket = new FruitBasket(); //Create a new fruit basket
$fruit_basket->basket = $fruits; //Assign the $fruits array to its 'basket' property

echo $fruit_basket->basket['banana']->color;    //prints 'yellow'

【讨论】:

  • 展示如何访问数组元素及其属性的好示例。接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 1970-01-01
相关资源
最近更新 更多