scripting - PHP Singleton or static cross-scripts -


so have classes need initialized once fill them data. want access them seperately ajax without having them initialized again. read singleton in php, wonder if it's possible have same instance of class in multiple scripts, can called seperatedly. example:

<?php class example {     private $instance;     private $a;      public function __construct() {}     public function __clone() {}     public function singleton() {         if (self::$instance === null) {              self::$instance = new example;         return self::$instance;     }     public function seta($val) {         $this->a = $val;     }     public function geta() {         return $this->a;     } } ?> 

script_a.php:

<?php include_once('example.class.php'); example::singleton()->seta(10); ?> 

script_b.php:

<?php include_once('example.class.php'); echo example::singleton()->geta(); // output 10? ?> 

i read static functions deleted memory @ end of script execution, apply singleton? if so, there way make above happen?

singleton not preserve state on multiple requests - should use sessions that. once use session there no point in using singleton pattern.

a simple solution:

script_a.php:

<?php session_start(); $_session['a'] = 10; ?> 

script_b.php:

<?php session_start(); if(isset($_session['a'])) {     echo $_session['a'];     // rest of processing } ?> 

sessions ok if not sharing data between multiple clients (good single client - multiple requests).
way of preserving state on multiple requests shared across clients caching (you can cache scalars, arrays, db connections or objects) , check more on link


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -