문제

I have a class with a private member "description" but that proposes a setter :

class Foo {
  private $description;

  public function setDescription($description) { 
    $this->description = $description; 
  }
}

I have the name of the member in a variable. I would like to access the field dynamically. If the field was simply public I could do :

$bar = "description";
$f = new Foo();
$f->$bar = "asdf";

but I don't know how to do in the case I have only a setter.

도움이 되었습니까?

해결책

<?php
$bar = "description";
$f = new Foo();
$func="set"+ucwords($bar);
$f->$func("asdf");
?>

다른 팁

Try this:

$bar = 'description';
$f = new Foo();
$f->{'set'.ucwords($bar)}('test');

Use magic setter

class Foo {
  private $description;

  function __set($name,$value)
  {
    $this->$name = $value;
  }  
/*public function setDescription($description) { 
    $this->description = $description; 
  }*/
}

but by this way your all private properties will act as public ones if you want it for just description use this

class Foo {
      private $description;

      function __set($name,$value)
      {
        if($name == 'description')
        { $this->$name = $value;
          return true;
         }
         else 
        return false
      }  
    /*public function setDescription($description) { 
        $this->description = $description; 
      }*/
    }

This function come do the job:

  private function bindEntityValues(Product $entity, array $data) {
      foreach ($data as $key => $value){
        $funcName = 'set'+ucwords($key);
        if(method_exists($entity, $funcName)) $entity->$funcName($value);
      }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top