PHP: How to use dynamic variable name with a class' setter
Asked Answered
V

4

6

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.

Vamoose answered 23/7, 2012 at 12:39 Comment(1)
Look into Reflection ;) php.net/manual/en/reflectionproperty.setvalue.php - edit, actually could you not use $f->{$bar} = "asdf";?Pidgin
B
11
<?php
$bar = "description";
$f = new Foo();
$func="set"+ucwords($bar);
$f->$func("asdf");
?>
Bullfrog answered 23/7, 2012 at 12:42 Comment(1)
Thank you very much. It was actually straightforward but I didn't dare do that (I am used to C++) :)Vamoose
K
4

Try this:

$bar = 'description';
$f = new Foo();
$f->{'set'.ucwords($bar)}('test');
Krahmer answered 23/7, 2012 at 12:44 Comment(0)
P
1

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);
      }
    }
Pyroconductivity answered 6/11, 2018 at 3:8 Comment(0)
A
0

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; 
      }*/
    }
Admittedly answered 23/7, 2012 at 12:43 Comment(2)
Ok, but why not put them public then ? sorry it might be a newbie question.Vamoose
@Vamoose not so fancy as you think :)Admittedly

© 2022 - 2024 — McMap. All rights reserved.