tags:

views:

123

answers:

5

I'm looking to create an array or list with elements of a certain type (eg objects the implement a certain interface). I know I can create an object that does the same thing implementing Traversable and Iterator, or override ArrayObject. But maybe there's another way I have missed.

+4  A: 

Do you mean something like:

$array=Array();
foreach ($itemsToAdd as $item) {
    if ($item instanceof NameOfwantedInterface) {
     Array_push($array,$item);
    }
}

If you don't, them I'm sorry - it's just that your question isn't too clear.

Richy C.
Yes that's the idea I'm looking for the enforce in a contract.
koen
PHP doesn't specifically assign types to arrays. This much be checked manually with a fuction like this.
contagious
A: 

You could use type hinting:

<?php

interface Shape
{
    function draw();
}

class MyArray
{
    private $array = array();

    function addValue(Shape $shape) //The hinting happens here
    {
     $array[] = $shape;
    }
}

?>

This example is not perfect, but you'll get the idea.

MrHus
+3  A: 

I would write a custom class that extended ArrayObject and threw an exception if you tried to assign a variable that wasn't the correct type, there's really no better way to do it that I can think of.

Kane Wallmann
+1  A: 

PHP as a lanugage is very flexible in terms of type handling and type conversion. You will probably have to put a manual check in if you want any kind of strong type checking, a simple if statement will do.

The array object is designed to be especially flexible (lazy key assignment, automatic increment, string or integer keys, etc.) so you should probably use a custom object of your own.

Fire Crow
A: 

Basically, you are going to want to do a function that checks if the variable you are inserting into the array is an object.

function add($var)
{
    if(is_object($var))
    {
       $this->array[] = $var;
    }
}

If you want to make sure it has a specific class name, you would do something like this (for PHP5):

function add(className $var)
{
   $this->array[] = $var;
}

or this for previous PHP versions:

function add($var)
{
    if($var instanceOf className)
     {
        $this->array[] = $var
     }
}

You might want to look into array_filter() to do this without building an object.

Looking at that page, I've found that you can use array_filter with common functions like is_object. So doing something like this:

$this->array = array_filter($this->array ,'is_object');

Would filter the array to contain only objects.

Chacha102