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?
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?
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.
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.
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.
Create a third function C that calls A and then B, and use that new function all over the place. In OOP terms, A and B should be protected in your class and C is public, e.g. available for whoever uses your class.
The observer pattern can be used to do what you want (notify observers the event is going to happen so they can do something).