Call method once?

Hi guys,

I have a custom made class.
and this class is called repeatedly in the program.
and there is a method which define the array, below is the codes of this method.

public function set_array_container()
    {
        $this->array_container = array('apple', 'orange', 'mango', 'banana', 'guyabano');
        $this->save_array_2_session();
    }

I want this method to be called once while this method
is inside a class that is being called repeatedly.
How do I call this method once?

thanks in advance.

What you want is called a Singleton. I have not touched PHP in many years but there are some great resources on the subject. Here is one I found with a quick Google search.

Simply put, you use a ‘static’ class method as a flag to keep track if the class is currently instantiated.

This is the quick and dirty way.

public function set_array_container()
    {
        static $executed = false;
        if(!$executed) {
          $executed = true;
          $this->array_container = array('apple', 'orange', 'mango', 'banana', 'guyabano');
          $this->ave_array_2_session();
        }
    }

In theory though the callee should be responsible for limiting calls to this method not the method itself.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.