2011-02-23 34 views

回答

4

編號PHP沒有任何強類型。

我可以考慮強制執行此操作的唯一方法是讓CarArray類具有getter,setter等等。強制參數成爲Car類的函數。

+0

好想法。 SPL中有一個[ArrayObject](http://www.php.net/manual/en/arrayobject.construct.php)類可能有幫助 –

2

開箱即用,但是您可以在Car類上實現ArrayObject,並覆蓋ArrayObject的append方法以僅接受例如CarPart的實例。這樣你就有一個對象,它的行爲就像一個數組,只要你添加附加條目,它只會接受CarPart類型的條目。

0

你可以像下面這樣實現一個基本的列表類,並且只允許使用代碼中的addItem函數將項添加到列表中。你可以在它周圍添加很多功能。然後使用標準php數組功能對$list->items陣列執行任何陣列特定的操作。

class list() 
{ 
    function __construct($type) 
    { 
     $this->type = $type; 
     $this->items = array(); 
    } 

    public function addItem($item) 
    { 
     if(get_class($item) == $type) 
     { 
      $this->items[] = $item; 
     } 
     else 
     { 
      return false; 
     } 
    } 
} 
0

只是包裝任何你想要的車在內含typehinted API:

class Cars implements IteratorAggregate 
{ 
    protected $storage; 

    public function __construct(SplObjectStorage $storage) 
    { 
     $this->storage = $storage; 
    } 
    public function addCar(Car $car) 
    { 
     $this->storage->attach($car); 
    } 
    public function removeCar(Car $car) 
    { 
     $this->storage->detach($car); 
    } 
    public function getIterator() 
    { 
     return clone $this->storage; 
    } 
    // … 
} 

無論您使用SplObjectStorageArrayObject$storage普通array是你。這是包裝,正在照顧,只有Cars進入它。

Full working example on codepad

如果你喜歡使用數組表示法,例如方括號,執行ArrayAccess

class Cars implements IteratorAggregate, ArrayAccess 
{ 
    // … 

    public function offsetSet($offset, $value) 
    { 
     if($value instanceof Car) { 
      $this->storage[$offset] = $value; 
     } else { 
      throw … 
     } 
    } 
} 

Full working example at codepad

0

下面是使用陣列濾器以除去不屬於汽車的任何對象的簡單解決方案。

// Return TRUE to keep the value, FALSE otherwise 
function car_filter($val) { 
    return ($val instanceof Car); 
} 

$cars = array(...); // an array of cars 

// Apply the filter 
$cars = array_filter($cars, "car_filter") 
相關問題