PHP nasıl tam bir kez bir kod bloğu yürütebilirsiniz?

3 Cevap

Ben bir sınıf tanımı ile bir main.php dosyası var. Diğer php dosyaları bu main.php dosyayı kullanabilirsiniz

//main.php

<?php

class A{


}

//I want to execute the following statements exactly once    

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


?>

Ben gibi diğer php dosyalarında main.php kullanın

//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 Cevap

Gerçekten orijinal soru kabul edilen yanıt ile ilgilidir nasıl göremiyorum. Ben belirli bir kod daha bunu dahil üçüncü parti betikleri tarafından bir kez daha idam olmadığından emin olmak isterseniz, ben sadece bir bayrağı oluşturmak:

<?php

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

    define('FOO_EXECUTED', TRUE);
}

?>

Singleton desenleri, sadece bir sınıf instanciate tüm değişkenler aslında aynı tek örneğine işaret olduğunu zorlar.

Sana Singleton pattern gerekir düşünüyorum. Sadece sınıfın örneği bir kez yaratır ve aynı size bunu talep her zaman döndürür.

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:

Bu bakın:

The Singleton Design Pattern for PHP

Sadece bu bir sınıf yazdı.

Bu staticly denir beri app önyükleme düzeyinde dahil eğer değişken tüm uygulama boyunca ayrılmamak gerekir.

Ayrıca kodu kez belirli sayıda yürütmek için seçebilirsiniz.

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