简体   繁体   中英

PHP how to assign class property variables conditionally

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

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());
    ?>

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;

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.

$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.

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];
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM