简体   繁体   English

访问__get()魔术方法返回的数组的索引

[英]Accessing index of array returned by __get() magic method

I am trying to use the magic method __get() with a class in order to access a private property. 我试图将魔术方法__get()与类一起使用,以访问私有属性。 The property is not assigned a value unless it is accessed, and that value is an array which is indexed from 0. 除非访问该属性,否则不会为其分配值,并且该值是一个从0开始索引的数组。

class Foo {
    private $bar;

    public function __get($p) {
        if ($p == 'bar') {
            if ($this->bar) {
                return $this->bar;
            }
            else {
                return $this->bar = $this->get_bar();
            }
        }
    }

    private function get_bar() {
        return Array('a', 'b', 'c');    // data from db
    }
}

In my PHP code, I am instantiating an object of this class, and passing it directly to Smarty (ie $smarty->assign('obj', new Foo()) ). 在我的PHP代码中,我实例化了此类的对象,并将其直接传递给Smarty(即$smarty->assign('obj', new Foo()) )。 I would like to access the value at index 0 from the $bar property within my template file. 我想从模板文件中的$bar属性访问索引0处的值。 I have tried this: 我已经试过了:

    {$obj->bar[0]}

However, this is not returning anything for me... Is this something that is not supported by the data returned by this magic method? 但是,这并没有为我返回任何东西...这个魔术方法返回的数据不支持这种东西吗?

Sorry everyone! 对不起大家!

My problem was that, in the actual code, I was trying to access an array element which was actually embedded in an array one level deeper. 我的问题是,在实际的代码中,我试图访问实际上嵌入到更深一层的数组中的数组元素。

I was going to delete this question, however I feel as though it will be a good reference to demonstrate that an array returned by a magic method in this manner can be accessed with the standard subscript operator, even within a Smarty template. 我打算删除这个问题,但是我觉得这将是一个很好的参考,以证明即使使用Smarty模板,也可以使用标准下标运算符访问魔术方法返回的数组。

You cannot use $smarty->assign() to assign objects, assign() only accepts associative arrays and name value pairs. 您不能使用$smarty->assign()分配对象, assign()仅接受关联数组和名称/值对。 Use assign_by_ref() instead to send objects to your template. 使用assign_by_ref()代替将对象发送到模板。

PHP/Smarty Example PHP / Smarty示例

$foo = new Foo();
$smarty->assign_by_ref('obj', $foo);

Template Example/Useage 模板示例/用法

{$obj->bar[0]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM