0

我有一个 PHP 对象,其 id 不应更改,除非在一个特定上下文中,当调用特定方法时。但是这个方法在对象类之外,不能继承。我不知道正确执行此操作的更好方法是什么,如何“检查”对象设置器是否由正确的方法调用,以避免滥用?

在此先感谢您的帮助

编辑:这是一个例子:

<?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"?

}

...

}

?>
4

1 回答 1

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 */ }
}

?>
于 2013-05-28T15:20:59.963 回答