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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With