J
J
Just a Man2020-08-02 00:31:44
PHP
Just a Man, 2020-08-02 00:31:44

PHP getter setter as a function and with object parameter binding?

I will say in advance the question is not very stupid as it seems, but an interesting idea for implementation (for now we will not think about security and anything related to it)

The question is whether it is possible to pass an array to it when initializing a class (__construct) and after creating call the parameters of the one that the array will return or set as a getter setter but as an action?

well, it's like this:

$object = new Someclass(['id'=>1,'title'=>'Lorem ipsum set','category'=>2,'category_title'=>'Article']);
$title = $object->getTitle();
$object = $object->setTitle($title."some edits");


I don’t know for sure if it’s possible to make such a generator at runtime, but I came up with this solution
class Tester
{
  function __construct($arr)
  {
    foreach ($arr as $key => $value) {
      $this->$key = $value;
      $global = $value;
      $this->{"get".ucfirst(strtolower($key))} = (function() { return $this->{$value}; });  // если сделать return __FUNCTION__ то вернёт значение {closure}
    }
  }
    public function __call($method, $args)
    {
        if (isset($this->$method)) {
            $func = $this->$method;
            return call_user_func_array($func, $args);
        }
    }
}
$tester = new Tester(['id'=>1,'title'=>'Lorem ipsum set','category'=>2,'catTitle'=>'Article']);
echo $tester->getTitle();  // null


creating a separate class is not an option in the database, there is a lot of different data for each one, it is not possible to do it!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-08-02
@AnonymIty

https://www.php.net/manual/en/language.oop5.magic.php
In general, this is easily implemented
The constructor writes an array, a magic __call is done
https://github.com/Compolomus/Template/blob/master...

A
Anton Shamanov, 2020-08-02
@SilenceOfWinter

The database has a lot of different data for each to do is not possible!
you're not right, Uncle Fedor, you're eating this sandwich - you don't have to play around with magic, but write "scaffold" - a generator of model classes based on these tables. see gii in Yii2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question