Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if function has been called yet

Tags:

oop

php

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?

like image 687
Ben Shelock Avatar asked Dec 19 '09 14:12

Ben Shelock


People also ask

How do you check if a function is called in PHP?

The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.

When a function is called in Python?

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result.

How do you check if a function is executed in Javascript?

You can drop the == true since they both return booleans. If this condition if (function1() && function2() ){ is true, it means that these functions was executed and returned true.


2 Answers

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.

like image 57
Adam Liss Avatar answered Nov 02 '22 05:11

Adam Liss


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.

like image 35
Gordon Avatar answered Nov 02 '22 03:11

Gordon