为什么我们在 php 中使用 getter 和 setter?

why we use getter and setter in php?

//If it doesn't chech if its a normal old type setter ot getter
//Getting and setting with $this->getProperty($optional);
//Getting and setting with $this->setProperty($optional);

为什么要这样用?我们可以使用正常功能。

A getter 允许您 GET 值(读取它),并且 setter 允许您 SET 值(写入)

如果您在 class 中有一个 "myVariable" 字段,要从您的 class 外部访问该变量,您可以:

  • 将字段 public => 任何人都可以自由访问,因此第三方可以做任何事情 (例如:与您打算稍后进行的处理相比,将变量置于不连贯的状态)
  • 保留字段私有,定义 public 方法 getMaVariable 和 setMaVariable => 稍微重一些,但可以定义 get 而不是 set(-> 只读),完全控制执行的操作变量的值:控制值非零),与 "simple" 读取或写入相比,可以定义额外的操作(例如,真正的缺点:计数器的递增)...