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

前端 未结 3 1494
情深已故
情深已故 2020-12-30 09:29

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

//main.php



        
相关标签:
3条回答
  • 2020-12-30 09:43

    Just wrote a class for this.

    Since it is called staticly the variable should stick around through the entire application if included in the bootstrap level of your app.

    You can also choose to execute code a specific number of times.

    class exec{    
      public static $ids = array();
      public static function once($id){
        if(isset(static::$ids[$id])){
          return false;
        } else {
          if(isset(static::$ids[$id])){
            static::$ids[$id]++;
          } else {
            static::$ids[$id] = 1;
          }
          return true;
        }
      }
      public static function times($id, $count=1){
        if(isset(static::$ids[$id])){
          if($count == static::$ids[$id]){
            return false;
          } else {
            static::$ids[$id]++;
            return true;
          }
        } else {
          static::$ids[$id] = 1;
          return true;
        }
      }
    }
    
    //usage
    
    foreach(array('x', 'y', 'z') as $value){
      if(exec::once('tag')){
        echo $value;
      }
    }
    
    //outputs x
    
    foreach(array('x', 'y', 'z') as $value){
      if(exec::times('tag2', 2)){
        echo $value;
      }
    }
    
    //outputs xy
    
    0 讨论(0)
  • 2020-12-30 09:47

    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.

    0 讨论(0)
  • 2020-12-30 10:00

    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

    0 讨论(0)
提交回复
热议问题