views:

23

answers:

2

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 executed.

+5  A: 

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.

Wrikken
A: 

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
}
nikic