Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute a block of code exactly once in PHP?

Tags:

php

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?

like image 581
Bruce Avatar asked Apr 30 '10 09:04

Bruce


2 Answers

One way to make sure that certain code is not executed more than once by third-party scripts that include it, is to create a flag:

if (!defined('FOO_EXECUTED')) {
    foo();
    define('FOO_EXECUTED', true);
}

The Singleton pattern mentioned elsewhere just forces that all variables that instantiate one class actually point to the same only instance.

like image 138
Álvaro González Avatar answered Sep 19 '22 05:09

Álvaro González


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

like image 33
Sarfraz Avatar answered Sep 20 '22 05:09

Sarfraz