tags:

views:

98

answers:

2

I have one main.php file with a class definition. Other php files use this main.php file

//main.php

<?php

class A{


}

//I want to execute the following statements exactly once    

$a = new A();
/*
Some code 
*/


?>

I use main.php in other php files like

//php1.php
<?php
require_once("main.php");

$b = new A();

/* 
Some code
*/

?>

//php2.php
<?php
require_once("main.php");

$b = new A();

/* 
Some code
*/

?>

Is there any statement in PHP like execute_once()? How do I solve this?

+3  A: 

I think you need the Singleton pattern. It creates just once instance of the class and returns you the same every time you request it.

In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.

Update Based On OP Comment:

Please see this:

The Singleton Design Pattern for PHP

Sarfraz
How do I implement it in PHP? I got the theory but how do I implement it?
Bruce
@Jack googling for the PHP singleton doesn't help?
Col. Shrapnel
@Jack: Please see my updated answer. Thanks
Sarfraz
@Col. Shrapnel: It definitely should help :)
Sarfraz
You might want to add that the Singleton pattern is considered an AntiPattern by a growing number of people. Friends don't let friends use Singletons.
Gordon
@Gordon: yup, i have added the whole paragraph now, and yes it was important to show that too :)
Sarfraz
@Sarfraz why the complexity?
Codex73
+2  A: 

I cannot really see how the original question relates to the accepted answer. If I want to make sure that certain code is not executed more than once by third-party scripts that include it, I just create a flag:

<?php

if( !defined('FOO_EXECUTED') ){
    foo();

    define('FOO_EXECUTED', TRUE);
}

?>

The Singleton patterns just forces that all variables that instanciate one class actually point to the same only instance.

Álvaro G. Vicario
i would really have to agree with you...less overhead here IMO
espais