Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created January 3, 2018 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/ebd8fe13cc30f629fe34966d1ee70076 to your computer and use it in GitHub Desktop.
Save kobus1998/ebd8fe13cc30f629fe34966d1ee70076 to your computer and use it in GitHub Desktop.
Managing instance by using traits
<?php
/**
* Example class
*/
class Best
{
use Manager;
public $name;
function __construct ($name)
{
$this->add($name);
$this->name = $name;
}
}
<?php
/**
* Save instances staticly
* per class without having
* to extend or add code
* to all classes you want
* to save the instances of
*/
trait Manager
{
protected static $instances;
protected function add ($name)
{
self::$instances[$name] = $this;
}
public function get ($name = null)
{
if ($name != null)
{
return self::$instances[$name];
}
return self::$instances;
}
}
<?php
/**
* Example class
*/
class Test
{
use Manager;
public $name;
function __construct ($name)
{
$this->add($name);
$this->name = $name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment