Zend Framework Coding Standard

It is considered bad form in the Zend Framework coding standard to use public properties. It is correct to use private properties and public methods to work with them.

class MyClass
    public  $email;
    private $_name;
    public function setName($name)
        $this->_name = $name;
    public function getName()
        return $this->_name;
$my = new MyClass();
$my->email = '[email protected]';   //  
$my->setName('');          // 

Why is working with public properties discouraged?

Answer 1, authority 100%

To always be able to track the change of a variable in ONE place. If so, ban it. With public, your assignments will be lying around all over the code, I’m already silent about the fact that sometimes it’s very easy to mess up in this way. For example, by assigning uncleaned information from POST or GET to the property.
Personally, I generally use the magic methods __set, __getso as not to bother.

Answer 2, authority 50%

For encapsulation. In general, read McConnell’s “Perfect Code”, the book answers the question “what is good and what is bad” quite well.

Answer 3

Sometimes you can use publicproperties for classes that are not in the “core”, especially if you understand that the specified publicproperty can be set from anywhere on the object. When there are a lot of get* and set* methods, this is also bad. The implementation of properties in PHP __setand __getcomes to the rescue.

You asked in the comments:

How do you process incoming data? switchem?

No, for example, you create an internal array in the class:

protected $_properties = [];

Handlers like this:

public function __get($property)
    if (!array_key_exists($property, $this->_properties)) {
        throw new Exception("Specified property \"$property\" is not in the row");
    return $this->_properties[$property];
public function __set($property, $value)
    if ($this->isReadonly($property)){
        throw new Exception("Specified property \"$property\" is read only.");
    /* ...         ...*/
    $this->_properties[$property] = $value;
    return $this;

This is how a lot of things work in Zend itself – for example, their implementation of ActiveRecord. Let me explain – ActiveRecord is an object representation of a row in the database. For example, it is very convenient to do this:

$row->title = "Some title";
$row->date = date('Y-m-d H:i:s');

Moral– The get* and set* methods are only good to a small extent. Their use is not dynamic, they hurt the visibility of the class (which contains these methods), especially if the class violates the SRP. For flexible readable code – implement properties with __setand __get.