A
A
Alexander Shapoval2017-06-23 05:24:35
PHP
Alexander Shapoval, 2017-06-23 05:24:35

How to show object property in twig?

The situation is this, before using twig the class looked like this

class User
{
    public $data = [];

    public function __construct($id)
    {
        $this->id = $id;
        $this->data = $this->getData();
    }
    private function getData()
    {
        return [];
    }
    public function __get($name)
    {
        if (isset($this->data[$name])) {
            return $this->data[$name];
        }
    }
}

And I received the data for example like this
$user = new User(1);
echo $user->first_name;

In twig it does not work like this if you write
{{user.first_name}}
he needs something like this
class User
{
    public $data = [];
    public $first_name;

    public function __construct($id)
    {
        $this->id = $id;
        $this->data = $this->getData();
        $this->first_name = $this->data['first_name'];
    }
    private function getData()
    {
        return ['first_name' => 'Йаволь'];
    }
    public function __get($name)
    {
        if (isset($this->data[$name])) {
            return $this->data[$name];
        }
    }
}

Should I now write all the properties like this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2017-06-23
@sanek_os9

1. If you're playing magic, $data should be made private, not public.
2. if you play magic, then play to the end - where is the __isset() method ?
3. use manual luke - https://twig.sensiolabs.org/doc/2.x/recipes.html#u...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question