note 78766 deleted from language.oop5.decon by levim

From: Date: Tue, 18 Mar 2014 02:09:16 +0000
Subject: note 78766 deleted from language.oop5.decon by levim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-198918@lists.php.net to get a copy of this message
Note Submitter: randallgirard at hotmail dot com ---- I've been working on a project for a while now, and for example in my DB handler I wanted to load var's to the objects late; However, without doing it manually on the object itself but through a single static call. For other reasons, in my Sessions I then wanted to end them early without registering a shutdown routine for every possible session. Hence, I needed a way to track EVERY instance or object of the class. (Of course in a normal website design, this would be overly coded. It's more of a framework for a CMS, Daemon service, anything I wanna create etc...) <?php class example { public static $OBJS = array(); public $id; public function __construct() { example::$OBJS[] = $this; # I actually use a 'lastKey' routine here, but in this example the following should work: $this->id = key( array_slice(example::$OBJS, count(example::$OBJS) -1, 1, true) ); } public function __destruct() { $this->close(); } # unset the tracked object private function destruct() { if ( isset(example::$OBJS[$this->id]) ) unset(example::$OBJS[$this->id]); } # public shutdown routine public function close() { if ( isset($this->destructed) ) return; # ... $this->destruct(); $this->destructed = true; } } ?> You could then also use register_shutdown_function(...) to call a static class method, which loops through ALL the objects and calls the $obj->close routine. <?php # register a shutdown function which triggers before destructors (hence when such results are desired for a Session class, etc) register_shutdown_function("example::destructors"); class example { # ... see above code example # static class method to destruct all objects public static function destructors() { foreach ( example::$OBJS as $obj ) $obj->destruct(); } } This will probably give some people new ideas, and other will probably be confused. Happy coding... NOTE: I didn't test the code(s) above. They were a rewritten example from my frameworks. ?>

« previous php.notes (#198918) next »