I got carried away and talked about indexed arrays when I meant just passing paramaters.
what I meant to post was
I would go with passing non array parameters to set the initial properties you want and then use setters to set the rest of the properties when necessary.
if you use an associative array you will have to know the exact names of the properties in the class to set as the keys in the array
I’m not sure what you’re looking for here, the way to pass an arbitrary number of variables to the constructor that will be converted to some sort of private/protected members or you want to pass an arbitrary number of variables and check whether those that were passed contain ones you mark as required? Anyway, in order to shorten your argument list in the constructor, you can go around the problem like this:
private $members;
public function __construct(array $arguments = null)
{
if(!is_null($arguments))
{
foreach($arguments as $key => $value)
{
$this->$key = $value;
}
}
}
public function __set($key, $value)
{
$this->members[$key] = $value;
}
I don’t know whether the explanation is needed here, but I’ll post one anyway:
So, the constructor can take an array or nothing as the parameter. If you pass a string and so on, you’ll get an error.
That way, you can now construct your object such as this:
What setter will do is that it’ll set the innaccessible properties to certain values. Array indexes “id”, “title”, “code” are not defined as member variables in your class.
Hence, magic function __set() will be invoked and it’ll populate $members variable with the data.
If you need further processing, such as checking whether certain fields were passed to the constructor - it’s trivial, so I won’t post the example.