开发者

is it possible to change method property from public to private and back on runtime from inside class?

开发者 https://www.devze.com 2023-01-08 11:12 出处:网络
like this: if ($sth) make_private($this->method); or maybe there\'s some other way to affect accessibility of methods ?

like this: if ($sth) make_private($this->method);

or maybe there's some other way to affect accessibility of methods ?

Problem is that I written a class where methods must be called once, so I need code to restrict access to given method from outside the class after this method was 开发者_C百科executed.


You've got several better options:

  1. Handle the 'can only be called once' with some static state variable in the class itself, and throw legible exceptions.
  2. Handle the 'can only be called once' with a decorator object if you cannot alter the class/object itself.

The very undesirable way you suggest is possible, see classkit_method_redefine or runkit_method_redefine, but on behalf of anyone possibly working on your code in future: please do not use it.


Simple way to do so within the mothod (restrict to one call):

public function fooBar() {
     static $called;
     if (isset($called)) throw new Exception('Called already once!');
     $called = true;

     // your code
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号