【问题标题】:How to make a PHP Class Property only changeable by a class Method如何使 PHP 类属性只能由类方法更改
【发布时间】:2014-01-05 23:30:07
【问题描述】:
class Item {
     public $itemname;

     somekeyword $error; //The correct keyword I want to find

     public function insertData() {
          $query = "INSERT INTO table VALUES ('".$this->itemname."')";

          try {

                  //HERE THERE IS A NICE CODE TO EXECUTE THE QUERY AND SO...
                  return true; //Returns true on success
          } catch(PDOExecption e) {
                 $this->error = $PDOObject->errorInfo();
                 return false; //Returns false on FAIL but the Object has a property with the error information
          }

     }

}

我怎样才能使属性错误只能针对此类方法进行更改?我不希望它在外部被另一个类或文件更改。

关键字“受保护”是否可以使其在外部可读但不可更改?

谢谢!

【问题讨论】:

  • 离题,但您的代码可能容易受到 sql 注入的影响。
  • 谢谢 Matthew,是的,我只是为示例编写了这样的代码,但在实际代码中,我已经准备好了语句和安全验证!

标签: php class properties


【解决方案1】:

protected 使其无法从外部访问,PHP 中的属性没有只读关键字,要获取其值,您必须定义 getter 函数:

class Item {
     protected $error; 
     public function getError(){
         return $this->error;
     }
}

或使用一些“魔法”:

class Item {
     protected $error; 
     public function __get($name){
         return $this->$name;
     }
}

后者允许您仅通过 $object->error; 访问此属性,但与预定义的函数调用相比,可读性较差且速度稍慢。

【讨论】:

    【解决方案2】:

    您想要私有或受保护。如果您希望扩展您的类的类可以访问它,则为受保护的,否则为私有的。

    http://www.php.net/manual/en/language.oop5.inheritance.php

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      相关资源
      最近更新 更多