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

时间:2013-12-05 09:39:35

标签: php yii

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

 public class Distribute
    {

        public string Alias { get; set; }
        public string Count { get; set; }

   }

    public List<Distribute> States { get; set; }

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

1 个答案:

答案 0 :(得分:3)

也许您可以使用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);