如何使用php为类变量创建List对象



在c#中,我们可以选择用以下方法为类变量创建列表对象,

 public class Distribute
    {
        public string Alias { get; set; }
        public string Count { get; set; }
   }
    public List<Distribute> States { get; set; }

所以我的问题是,如何使用yii框架在php中实现上述代码?提前感谢!

也许您可以使用SplDoublyLinkedList类或ArrayAccess接口,然后覆盖元素集方法(push/offsetSet

class ListContainer extends SplDoublyLinkedList
{
    protected $type;
    public function __construct($listType)
    {
        $this->type = $listType;
    }
    public function push($value)
    {
        if (!$value instanceof $this->type) {
            throw new Exception('Element must be instance of ' . $this->type);
        }
        parent::push($value);
    }
    public function offsetSet($index , $value)
    {
        if (!$value instanceof $this->type) {
            throw new Exception('Element must be instance of ' . $this->type);
        }
        parent::offsetSet($index, $value);
    }
}
class Distribute
{
    public $alias;
    public $count;
}
$states = new ListContainer('Distribute');
$dist   = new Distribute;
$dist->alias = 'd1';
$dist->count = 17;
$states->push($dist);

最新更新