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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With