W
W
WQP2017-07-24 11:33:56
PHP
WQP, 2017-07-24 11:33:56

Is it correct to use __call like this?

Hello. How correct is it to use __call in this case (class below)? There will be several set methods and I would not like to return $this every time when it can be done only 1 time

Class A
class A
{
    protected $data;

    public function __call($name, $arguments)
    {
        if ( method_exists($this, $name) ) {
            call_user_func_array([$this, $name], $arguments);
        }

        return $this;
    }
    
    public function get()
    {
        return $this->data;
    }

    protected function setPreset()
    {
        // тут код манипуляции с $data, без return
    }
}

$A = new A();

$data = $A->setPreset()
          ->get();

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry MiksIr, 2017-07-24
@miksir

__call is called only if there is no method in the class, so in your case there will be different behavior when accessing an object from the outside and when accessing it inside the class, which is not good.
For the sake of saving one line with return, this is not worth doing.
If you really do, then completely remove the magic setPreset altogether, or use an IDE that can generate a fluent setter

A
Alexey Ukolov, 2017-07-24
@alexey-m-ukolov

In my opinion, the ratio of the principle of least surprise to the usefulness of such an approach is unacceptable and I would not write like that.
The code becomes less clear, you need to write a doc block with for each set method (so that the IDE does not go crazy), which completely kills all the profit. Well, it imposes a certain performance overhead. /** @return self */

N
nepster-web, 2017-07-24
@nepster-web

Try not to use magic and inheritance at all, as well as setters.
1 - ide can generate everything itself. If you can't, change your text editor to ide.
2 - magic leads to things that are not obvious and the complexity of testing
3 - be careful with setters, use them less often, and put everything in the constructor.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question