Is it possible to automatically generate Getter / Setter from array values ​​in PHP?

So I have some arrays

$array_1 = Array('one','two','three');
$array_2 = Array('red','blue','green');

Is there a dynamic way to create Setters and Getters for an array with single values?

Thus, the class will look something like this:

class xFromArray() {

}

So, if above, if I passed $ array_1, it would generate something like this:

private $one;

setOne($x) {
   $one = $x;
}

getOne() {
   return $one;
}

if I passed $ array_2, it will generate something like this:

private $red;

setRed($x) {
   $red = $x;
}

getRed() {
   return $red;
}

So would I call it anyway? (My best guess, but that doesn't seem to work)

$xFromArray = new xFromArray;
foreach($array_1 as $key=>$data) {
   $xFromArray->create_function(set.ucfirst($data)($data));
   echo $xFromArray->create_function(get.ucfirst($data));
}
+3
source share
2 answers

You can use __call()to call dynamic methods. So:

class Wrapper {
  private $properties;

  public function __construct(array $names) {
    $this->properties = array_combine(array_keys($names),
      array_fill(0, count($names), null));
  }

  public function __call($name, $args) {
    if (preg_match('!(get|set)(\w+)!', $name, $match)) {
      $prop = lcfirst($match[2]);
      if ($match[1] == 'get') {
        if (count($args) != 0) {
          throw new Exception("Method '$name' expected 0 arguments, got " . count($args));
        }
        return $properties[$prop];
      } else {
        if (count($args) != 1) {
          throw new Exception("Method '$name' expected 1 argument, got " . count($args));
        }
        $properties[$prop] = $args[0];
      }
    } else {
      throw new Exception("Unknown method $name");
    }
  }
}

PHP. __get() __set() , ( , ) .

:, , __call() , , , . :

$wrapper = new Wrapper($array_1);
$wrapper->setOne("foo");
echo $wrapper->getOne(); // foo
$wrapper->getAbc(); // exception, property doesn't exist

__call() . get set, ( ), , , . , , .

. Overloading PHP "" .

+7

__call() ( __set() & __get()), .

+2

Source: https://habr.com/ru/post/1749042/


All Articles