Php 如何正确地迭代Mustach中具有私有属性的对象数组?

Php 如何正确地迭代Mustach中具有私有属性的对象数组?,php,mustache.php,Php,Mustache.php,小胡子模板示例: {{#entites}} <a href="{{url}}">{{title}}</a> {{/entities}} 基本嵌套数组 $data = [ 'entities' => [ [ 'title' => 'title value', 'url' => 'url value', ] ] ]; 这在模板中正确呈现 类的对象数组: class Ent

小胡子模板示例:

{{#entites}}
  <a href="{{url}}">{{title}}</a>
{{/entities}}
基本嵌套数组

$data = [
   'entities' => [
       [
         'title' => 'title value',
         'url' => 'url value',
       ] 
    ]
];
这在模板中正确呈现

类的对象数组:

class Entity 
{
  private $title;

  private $url;

  //setter & getters

  public function __get($name)
  {
      return $this->$name;
  }
}
胡须参数:

$data = [
   'entities' => [
       $instance1
    ]
];

在这种情况下不工作-输出为空(属性中没有值)

而不是magic方法,为什么不在类中使用这样的函数呢

public function toArray()
{
    $vars = [];
    foreach($this as $varName => $varValue) {
        $vars[$varName] = $varValue;
    }

    return $vars;
}
然后调用该函数以获取作为数组的变量

$data = [
   'entities' => $instance1->toArray()
];
您可以使用Interface访问您的私有财产,如下所示:

class Foo implements ArrayAccess {
    private $x = 'hello';

    public $y = 'world';

    public function offsetExists ($offset) {}

    public function offsetGet ($offset) {
        return $this->$offset;
    }
    public function offsetSet ($offset, $value) {}
    public function offsetUnset ($offset) {}
}

$a = new Foo;

print_r($a); // Print: hello

当然,这是一个简单的例子,您需要为其余继承的方法添加更多的业务逻辑。

不清楚您在这里尝试做什么,但是,您尝试时会遇到什么错误?@hassan没有错误,只是呈现的属性为空-{url}&{{title}
private
变量仅在类实例中可用,因此您可以按照@Salvatore所说的操作,或者将属性设置为
public
。第三个选项是实现与此答案类似的
JsonSerializable
接口。@u\u mulder所以在这种情况下,\u\u get($name)不可能工作?通过实现_uget方法,我使它们在外部可用。我也有getter。
\uu get
在显式访问属性时有效。这意味着您应该编写类似于
'entities'=>[[['title'=>$instance1->title',url'=>$instance1->url]
@u_mulder好的,我想胡子可以帮我完成。Thanks@u_mulder如何实施ArrayAccess?
class Foo implements ArrayAccess {
    private $x = 'hello';

    public $y = 'world';

    public function offsetExists ($offset) {}

    public function offsetGet ($offset) {
        return $this->$offset;
    }
    public function offsetSet ($offset, $value) {}
    public function offsetUnset ($offset) {}
}

$a = new Foo;

print_r($a); // Print: hello