Why use getter setters for doctrine2 classes

Why do we usually use getter setters for doctrine2 classes to store and retrieve data?

as below:

<?php
// src/Product.php
class Product
{
    /**
     * @var int
     */
    protected $id;
    /**
     * @var string
     */
    protected $name;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

If we create properties of the public class, we can save the data without getter setters. Is not it?

<?php
// src/Product.php
class Product
{
    /**
     * @var int
     */
    public $id;
    /**
     * @var string
     */
    public $name;
}
+4
source share
3 answers

because class members (variables) are usually (and should be) private or protected.

Thus, we use the public set / get method to store and retrieve data from them that otherwise would not be available outside the class.

Giving class members a public place may lead to an unintentional revaluation, so we limit access to prevent this. Read on encapsulation.

/ , .

heres SO.

+1
  • - , . Doctrine.
  • Getters seters , .
  • getters seters - , , , PHP " ".
+4

SOLID- Doctrine. .

. :

<?php

class Product
{

    /**
     * @var int
     */
    private $id;

    /**
     * @var string
     */
    private $name;

    /**
     * @param int $id
     * @param string $name
     */
    public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

}

.

+2

All Articles