Check if function has been called yet

13,071

Solution 1

Language-agnostic answer:

Keep a (static or global) "state" variable and set a flag within the prerequisite function when it's called. Check the flag in the dependent function to decide whether it's allowed to run.

Solution 2

Well, the easiest solution would be to simply call this method before you run the method that needs it. If you do not want to run the method each time, but only when some internal state of your object applies, you'd do

class Foo
{
    protected $_someState = 'originalState';

    public function runMeFirst()
    {
        // code ...
        $this->_someState = 'changedState';
    }

    public function someMethod()
    {
        if(!$this->_someState === 'changedState') {
            $this->runMeFirst();
        }
        // other code ...
    }
}

As long as the method and state that needs to be checked and called are inside the same class as the method you want to call, the above is probably the best solution. Like suggested elsewhere, you could make the check for someState into a separate function in the class, but it's not absolutely necessary. I'd only do it, if I had to check the state from multiple locations to prevent code duplication, e.g. having to write the same if statement over and over again.

If the method call is dependent on state of an outside object, you have several options. Please tell us more about the scenario in that case, as it somewhat depends on the usecase.

Solution 3

The other function (the one, which should be called first) will manipulate some state, thats why the second function needs to know about that state. I don't know about a php builtin for that but I would eventually create another function, which returns information about that state, e.g. isReadyToRunSomething, isValid, hasConnection .. or whatever .. then use this function in the beginning of the second function, to see whether it is allowed to run.

Solution 4

The observer pattern can be used to do what you want (notify observers the event is going to happen so they can do something).

Share:
13,071
Ben Shelock
Author by

Ben Shelock

i do internets and that

Updated on June 14, 2022

Comments

  • Ben Shelock
    Ben Shelock almost 2 years

    New to OOP in PHP

    One of my functions requires another function to be executed before running. Is there a way I can check this?