Check if function has been called yet

前端 未结 5 2105
挽巷
挽巷 2020-12-20 23:02

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?

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 23:52

    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.

提交回复
热议问题