0

I have a class that I am writing and I have a method that I would like to run once per initiation of the class. Normally this would go in the construct method, but I only need it to run when I call certain methods, not all.

How would you all recommend I accomplish this?

3 Answers 3

3

Create a private property $methodHasBeenRun which has a defualt value of FALSE, and set it to TRUE in the method. At the start of the method, do:

if ($this->methodHasBeenRun) return; $this->methodHasBeenRun = TRUE; 
Sign up to request clarification or add additional context in comments.

Comments

1

You didn't specify exactly why you only want to run a given method once when certain methods are called, but I am going to make a guess that you're loading or initializing something (perhaps data that comes from a DB), and you don't need to waste cycles each time.

@DaveRandom provided a great answer that will work for sure. Here is another way you can do it:

class foo { protected function loadOnce() { // This will be initialied only once to NULL static $cache = NULL; // If the data === NULL, load it if($cache === NULL) { echo "loading data...\n"; $cache = array( 'key1' => 'key1 data', 'key2' => 'key2 data', 'key3' => 'key3 data' ); } // Return the data return $cache; } // Use the data given a key public function bar($key) { $data = $this->loadOnce(); echo $data[$key] . "\n"; } } $obj = new foo(); // Notice "loading data" only prints one time $obj->bar('key1'); $obj->bar('key2'); $obj->bar('key3'); 

The reason this works is that you declare your cache variable as static. There are several different ways to do this as well. You could make that a member variable of the class, etc.

Comments

-1

I would recommend this version

class example { function __construct($run_magic = false) { if($run_magic == true) { //Run your method which you want to call at initializing } //Your normale code } } 

so if you do not want to run it create the class like

new example(); 

if you want

new example(true); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.