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
}
}
}
如何使属性错误只能针对此类方法进行更改?我不希望它可以被其他类或文件在外部更改。
关键字“protected”是否可以使其在外部可读但不可更改?
谢谢!
最佳答案
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;
访问此属性,但可读性较差,并且比预定义函数调用稍慢。
关于php - 如何使 PHP 类属性只能通过类方法更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20940602/