Best way in PHP to ensure in a class that all the class functions are called only if a given condition is true -


i have class in each function of class have check exact same condition before executing code:

class myobject {     public function function1($argument)     {         if($condition === true)         {             //do         }     }      public function function2($argument)     {         if($condition === true)         {             //do         }     }      public function function3($argument)     {         if($condition === true)         {             //do         }     }      public function function4($argument)     {         if($condition === true)         {             //do         }     } } 

we can see function1, function2, function3, function4 execute code if $condition === true.

if in future add function called function5, have duplicate condition.

so question is, best way ensure before call function in class, condition true, , if condition false, not call function.

my method use magic function __call , make functions of class private:

class myobject {      public function __call($method,$args)     {         if($condition === true)         {             call_user_func_array(array($this,$method),$args);         }          return;     }      private function function1($argument)     {             //do     }      private function function2($argument)     {             //do     }      private function function3($argument)     {             //do     }      private function function4($argument)     {             //do     } } 

it seems work. however, i'm unsure work , clever way of doing it.

its pretty normal first way. but, maybe whole design of class wrong? if every single 1 function needs exact same condition true maybe set/check in constructor , treat there? why recheck condition multiple times? can change between function calls?

something used way:

    try{        $myclass = new myclass(); // if no permissions throw exception     }catch(exception $e){        //do        return false;     } //we know user permission go on     $myclass->function1();     $myclass->function2(); 

the second way works lose of power of phpdoc , editors autocomplete code. way have know name of every method.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -