2014-06-21 59 views
1

此声明的飞行性能:PHP使私有财产,因为他们得到声明

class metadata { 

    function __construct($file) { 
    /* Argument: Array containing data of a single file */ 
     while ($pointer = key($file)) { 
      $this->$pointer = current($file); 
      next($file); 
     } 
    } 
} 

我想这是在while循环$this->$pointer声明的所有属性是私有的。

我该如何做到这一点,而不需要设置很长的private $prop1, $prop2, $etc;

主要目的是保持代码简洁。我写的很可能需要20个私人物品,我只是想知道我是否可以保存打字。

+0

我相信你只能做,如果你预先声明数组作为私人&然后添加键,由于这里解释。 http://stackoverflow.com/a/1920524/117259 – JakeGould

+0

可能的重复[动态添加一个私有属性到一个对象](http://stackoverflow.com/questions/13415023/dynamically-add-a-private-property-到一个对象) –

回答

0

你可以使用stdclass。下面是官方的链接,http://us1.php.net//manual/en/reserved.classes.php 一样,

class metadata { 

    function __construct($file) { 
     private $this->file_meta = new stdClass(); 
     while ($pointer = key($file)) { 
      $this->file_meta->pointer = current($file); 
      next($file); 
     } 
     $this->file_meta->other_var = 'some value'; 
    } 
}