Re: Re: PHP class question
| From: | Nathan Rixham | Date: | Thu, 21 May 2009 23:59:34 +0000 |
| Subject: | Re: Re: PHP class question | ||
| References: | 1 2 3 4 5 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-292914@lists.php.net to get a copy of this message | ||
Shawn McKenzie wrote:
Shawn McKenzie wrote:bullseye, static is the way to approach when you only need a single instance however you don't always need to include a referent to the instance inside your class.. you can easily core::getInstance()->go() or core::go() and have class core store an instance of itself class core { var $instance; function getInstance() ..etc - been so long since i touched php4Peter van der Does wrote:I guess you could always do a singleton so that you always have the same instance. Add something like this to the core class (not tested): static $_instance; function getInstance() { if(self::$_instance === null) { self::$_instance = new self(); } return self::$_instance; } Then you can do: class A extends framework_class { var $core; function A() {On Thu, 21 May 2009 14:08:11 -0500 Shawn McKenzie <nospam@mckenzies.net> wrote:Well I guess from my point of view there are several ways depending upon the requirements. Others that are better with OOP will chime in I'm sure. This I'll get flamed for, but you can use one instance of core as a global: class A extends framework_class { var $core; function A() {This doesn't make sense. You say "class A needs to be extended with another class", however what you show below is "class A extending framework_class".I worded it wrong, I apologize. Class A needs to be an extension of the framework class.$this->core =& $GLOBALS['core']; $this->core->go();} } //in global scope in bootstrap or whatever $core = new core(); Along the same lines but more OOP and without globals, maybe use a registry class and store core in the registry. This also uses one instance of core: class Registry {protected $_objects = array();function set($name, &$object) { $this->_objects[$name] =& $object; }function &get($name) { return $this->_objects[$name]; }} class A extends framework_class { var $core; function A(&$registry) { //dunno if you need a reference here or not$this->core = $registry->get('core'); $this->core->go();} //i guess you could also pass in core, but registry will give you all objects in the registry //function A(&core) {//$this->core = $core; //$this->core->go();//} } //this is in your bootstrap or whatever $core = new core(); $registry = new registry(); $registry->set('core', $core); Or, if you don't need an object, call it statically: class A extends framework_class { function A() {core::go();} }$this->core = core::getInstance(); $this->core->go();} }