限制对象修改

时间:2013-05-28 13:58:02

标签: php object setter

我有一个带有id的PHP对象,除了在一个特定的上下文中,当调用特定的方法时,不应该更改它。但是这个方法在对象类之外,不能继承。我不知道什么是更好的方法来正确地做到这一点,我如何“检查”是否通过正确的方法调用对象设置器,以避免滥用?

提前感谢您的帮助

编辑:这是一个例子:

<?php

class myClass {

private $id;
private $var1;
private $var2;


private function setId($id){
    //this must be accessible only when calling "secureSetId()" from class "secureClass"
    $this->id = $id;

}


public function setVar1{
    //this is a public function...

}

...

}

class secureClass {


private function secureSetId($id){

    //this is accessible only here, but how to call private function "setId" from class "myClass"?

}

...

}

?>

1 个答案:

答案 0 :(得分:0)

<?php

interface SimpleMyClass {
  public function setVar1($value);
  public function setVar2($value);
}

interface SecureMyClass extends SimpleMyClass {
  public function setId($id);
}

class MyClass implements SecureMyClass {
  private $id;  
  private $var1;
  private $var2;

  public function setVar1($value) { /* ... */ }
  public function setVar2($value) { /* ... */ }
  public function setId($id) { /* setting id */ }
}

// classes that use "different versions" of MyClass

class SecureOtherClass {
  public function setMyClass(SecureMyClass $my) {  /* this class is able to set id of MyClass */ }
}

class SimpleOtherClass {
  public function setMyClass(SimpleMyClass $my) { /* this class uses simple version of MyClass */ }
}

?>