简体   繁体   中英

Is it correct using __call() instead of getters and setters?

On the subject of good practices, is it right to use __call() to classes that need getters and setters to their properties?

See an example of Doctrine Entity: https://gist.github.com/devmatheus/10668172#file-sessao1-php

I know that performance will be affected but this will decrease time in programming, what do you think?

As you said, the performance will be decreased, but better design always beats performance. A Server with more Ram and CPU isn't so expensive, like a Developer.

I think it is a good point, if you need dynamicly invoked methods. , but then, it should be well documented via PHP Doc (It helps IDEs for Code Completion, and Developers don't need 1 hour to understand) . This will only be the case, if you're not able to document it with this PHP Doc (What is the Methodname? What is the return type?)

/*
 * @method myReturnType $myMethodName
 * @property myReturnType $myPropertyName
 */
class Foo {}

If your Method can be staticly created, you should do this.

Your Gist is talking about getters and setters, that are automaticly created via __call , with no extra logic. The good thing about getters and setters is, you can work with the value, before you set or get it. In this case, you can not. So I would consider this bad design. If you would make the fields public instead of protected, it would have the same result.


Side Note : IDE's like PHP Storm can automaticly create Setter and Getter for you, if your wrting protected $_foo; (In this case simple press ALT+ENTER on the field.

Result:

protected $_foo;

/**
 * @return mixed
 */
public function getFoo()
{
    return $this->_foo;
}

/**
 * @param mixed $foo
 */
public function setFoo($foo)
{
    $this->_foo = $foo;
}

If you define the Type via PHP doc or via direct assignment ( protected $foo = true ), the generated PHP Doc even writes @param bool $foo and @return bool instead of mixed .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM