views:

265

answers:

6

Hi,

I'm new to php classes, arrays, etc, so pls excuse me if I don't use the correct terminology. What I'm looking for is how to assign easily values to properties from a class without having to depend on "if" statements.

For example:

Suppose I have an instance of a class test, and "test" has a property "employee" (hope this is the correct way to call it) and employee is of a complex type.

So, I have something like:

$test -> employee = array('Age' => '30', 'Sex' =>$sex, 'nationality'=>$nationality, 'maritalstatus'=>$status, etc, etc)

The problem I have here is, what if 'Age", 'Sex', 'Nationality', etc are not always present and I only want to assign values to them when they have something assigned, and I don't want to use If's for each combination of not empty values ...(this is a short example, but I have a lot of these attributes or whatever they are called and too many "if" combinations is too messy)...

I'm sending these values later as a soap request and I don't want any empty xml tags...

My apologies if my terminology is not correct, but I hope I've been clear enough for someone out there to help me out!

Thanks in advance, Pablo

A: 

How about this:

$array = array('Age' => '30' , 'Sex' => $sex, 'nationality' => $nationality, 'maritalstatus' => $status);
foreach ($array as $key => $value) { 
    if (is_null($value) || $value=="") { 
        unset($array[$key]); 
    } 
}
$test->employee = $array;
Eikern
+3  A: 

What you could do in this case:

  • Make employee a private attribute
  • Define a "setter" method setEmployee that requires all arguments to be provided.

Here is some example code; try this out:

    <?php

    class test{

        private $employee;

        public function setEmployee($age,$sex,$nationality,$maritalstatus){
            $this->employee=array('Age'=>$age,
                            'Sex'=>$sex,
                            'Nationality'=>$nationality,
                            'MaritalStatus'=>$maritalstatus);
        }

        public function getEmployee(){
            return $this->employee;
        }
    }


    $t=new test();
    $t->setEmployee('32','M','American','Married');

    print_r($t->getEmployee());
    ?>
AJ
I agree to this method if requiring each field is what they want. I was under the impression that they simply wanted to skip values which were null and in that case, I've posted my equivalent approach. It's good to see these OOP solutions.
erisco
Hi Erisco, Pablo here, you are correct, I just want to assign values that have been "selected" from a browser menu by a user. These values assigned are later sent as a soap request so I need to make sure that values not set are not later transformed into empty xml tags. There are many value combinations from the browser menu, so thats the reason for the actual "if's"I 'm trying to avoid. Thanks to everybody for your help, Pablo.
Pablo
A: 

Have you considered a short ternary solution?

'Sex' => ( isset($sex) ? $sex : "n/a" )

This is essentially performing if-else logic, but not nearly as verbose. Our condition is isset($sex). If this is true, we return $sex, else we return "n/a". Whatever is returned becomes the value of 'Sex'.

If this isn't sufficient, I would encourage you to require valid values during instantiation. If the user doesn't provide proper and expected values, refuse instantiation of the class.

Jonathan Sampson
A: 
$temp_array = array('Age' => '30', 'Sex' =>$sex, 'nationality'=>$nationality, 'maritalstatus'=>$status, etc, etc);

foreach($temp_array as $key => $val){
 if(!$temp_array[$key]){
  unset($temp_array[$key];
 }
}

if you need to accept FALSE as a value, then use this instead:

$temp_array = array('Age' => '30', 'Sex' =>$sex, 'nationality'=>$nationality, 'maritalstatus'=>$status, etc, etc);

foreach($temp_array as $key => $val){
 if($temp_array[$key] !== NULL){
  unset($temp_array[$key];
 }
}

edit: this makes sure only keys with non-null or non-falsey values are present in the final array.

Mike Sherov
A: 

One way would be to store your possible keys in an array - then you could iterate over it only need one set of control code for each array:

$keys = array('Age', 'Sex', 'Nationality');

foreach ($keys as $key) {
  if ( isset($inputs[$key]) )
    $test->employee[$key] = $inputs[$key];
}
marramgrass
A: 

I am a tad confused on your problem. Are the variables such as $sex, $nationality, and so forth not always defined or are they just sometimes set to null? If those variables do not always exist, it is imperative to check for their existence first and there is no way around that - unless you refactor earlier code.

I am presuming the variables do exist and you just do not want to save NULL cases.

An OOP approach may be to use data encapsulation - a common choice for a case like this. These following changes should be made to the test class.

class test {

  protected $employee = array();

  public function getEmployee() {
    return $this->employee;
  }

  public function setEmployee($employee) {
    foreach ($employee as $key => $value) {
      if ($value !== null) {  // or any value it should not be
        $this->employee[$key] = $value;
      }
    }
  }

...

Another approach would be to introduce employee as its own object, and use mechanisms in its object to skip null values. You might override __set, use data encapsulation again, take __construct arguments, or a variety of other solutions.

erisco