mjs mjs - 3 months ago 8
PHP Question

Passing arrays of varying size to setters/functions in Php

I am relatively new to PHP and have searched quite extensively but can't quite figure out the solution to my problem.

I am trying to figure out how to use setters in a class where the variable being set is an array of an unknown size. For example:

class Shirt
{
private $sizes=array();

public function setSizes($x)
{
$this->sizes=array($x);
}

}

$BlueShirt = new Shirt;
$BlueShirt -> setSizes (12,14,16);


The above code will only set the first size declared in the $BlueShirt object. In some cases shirt objects will have 3 sizes, others may have 3 or 4 and again others may have only 1. I know a simple solution would be to declare the array() in the object:

class Shirt
{
private $shirts;

public function setShirt($x);
{
$this->shirts=($x);
}
}

$BlueShirt = new Shirt;
$BlueShirt -> setShirt(array(12,14,16));


However, I really prefer not to go that route. I use this initial size data in other functions that return size ranges, etc. These functions require that the size data be in array form. I would much rather force the array as even with clear commenting, it may not be obvious to future users adding objects that objects with only one size should still be entered as an array.

Thanks for any help in advance.

Answer

What about :

class Shirt {

    private $sizes=array();

    public function setSizes() {
        $this->sizes=func_get_args();
    }

}

$BlueShirt = new Shirt;
$BlueShirt -> setSizes (12,14,16);

func_get_arg() get all the args passed to the function. But I don't understand why you don't want to directly give an array to the function.

Comments