关于php:我应该在getter/setter中使用private关键字还是public关键字?

Should I use private keyword or public keyword in getter/setter?

我还在学习OOP。我有一个顾虑就是使用getter和setter中使用的private关键字。根据我对private关键字的理解,它不能从类外访问。这里有一个从书上抄下来的片段!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
//GetSet.php
class GetSet
{
     private $dataWarehouse;
     function __construct()
     {
         $this->setter(200);
         $got= $this->getter();
         echo $got;
     }

     private function getter()
     {
         return $this->dataWarehouse;
     }

     private function setter($setValue)
     {
          $this->dataWarehouse=$setValue;
     }
}

$worker=new GetSet();

?>

但是,我在getter和setter中看到了很多使用公共关键字的情况。因此,这本书说,"如果我们在getter和setter中使用公共关键字,它可以打破封装概念"。

我的问题是"我应该在getter和setter中使用public还是private关键字?"还是基于业务需求?".


如果您有足够的getter和setter方法来处理该变量,那么我将使它成为私有的,以提高安全性。

这个程序员的问题也为使用私有变量提供了一些其他的实际参数。

A public member can be accessed from outside the class, which for practical considerations means"potentially anywhere". If something goes wrong with a public field, the culprit can be anywhere, and so in order to track down the bug, you may have to look at quite a lot of code.

A private member, by contrast, can only be accessed from inside the same class, so if something goes wrong with that, there is usually only one source file to look at. If you have a million lines of code in your project, but your classes are kept small, this can reduce your bug tracking effort by a factor of 1000.