A setter that can set an Array

In many cases you would probably create your own setter function to keep protected the variables inside the object, but one of the most annoying things with this is that setting arrays becomes something extremely hard since PHP does not let you use the [] to set a new value in the array.

I have created a setter with a solution for this scenario which is good, but not the best. With the setter bellow you can set a variable with an array or insert one element to the array (considering that the element uses numeric keys only).

public function __set($variable,$value){
try{
$variablesThatAreArrays = array(‘variable1′,’variable2’,’variable3”);
if(isset($variable) && in_array($variable,$variablesThatAreArrays)) {
// the current variable being set is an array
if(isset($value) && is_string($value)) {
$tmpArray = array();
if(isset($this->$variable) && is_array($this->$variable)) {
foreach($this->$variable as $key => $var){
$tmpArray[] = $var;
}
}
$tmpArray[] = $value;
$this->$variable = $tmpArray;
return true;
}
else if(isset($value) && is_array($value)){
$this->$variable = $value;
return true;
}
}

else if(is_string($variable) && strlen($variable) > 0 && isset($value) && (is_string($value) ||
is_numeric($value) || is_bool($value))){
// is a common variable
$this->$variable = $value;
return true;
}
$this->error = “Unable to set {$variable} variable.”;
return false;
}
catch(Exception $e){
$this->error = “Exception Handler Error: {$e->getMessage()}”;
return false;
}
}

If you have an object that uses this function you would use:

$obj->variable1 = ‘new value to be inserted into the array’;

to add a value into the array. The best way to interpret this is by:

$variable1[] = ‘new value to be inserted into the array’;

Another way to use the setter is by setting a full array. In this case the call would be $obj->variable1 = array();

Note: This method will work for PHP5. For more information read the article: Dynamic Methods in PHP from Josh Sharp

Advertisements

About mcloide

Making things simpler, just check: http://www.mcloide.com View all posts by mcloide

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: