简体   繁体   中英

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 a class in which each function of the class have to check the exact same condition before executing its code:

class myObject
{
    public function function1($argument)
    {
        if($condition === true)
        {
            //Do Something
        }
    }

    public function function2($argument)
    {
        if($condition === true)
        {
            //Do Something
        }
    }

    public function function3($argument)
    {
        if($condition === true)
        {
            //Do Something
        }
    }

    public function function4($argument)
    {
        if($condition === true)
        {
            //Do Something
        }
    }
}

We can see that function1, function2, function3, function4 only execute their code if $condition === true .

If in the future I add another function called function5, I will have to duplicate this condition.

So my question is, what is the best way to ensure that before call ANY function in the class, a condition is true, and if the condition is false, not call the function.

My method is to use the magic function __call and make all the functions of the 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 Something
    }

    private function function2($argument)
    {
            //Do Something
    }

    private function function3($argument)
    {
            //Do Something
    }

    private function function4($argument)
    {
            //Do Something
    }
}

It seems to work. However, I'm unsure that it will always work and that it is a clever way of doing it.

Its pretty normal to do it your first way. But, maybe the whole design of the class is wrong? If every single one function needs the exact same condition to be true maybe you could set/check it in the constructor and treat it from there? Why recheck the condition multiple times? Can it change between function calls?

Something like that would be used this way:

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

The second way works but you lose some of the power of phpdoc and good editors that will autocomplete your code. This way you have to know the name of every method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM