PHP beginner |
|
Hallo,
ik ben wat aan het proberen met singleton en dit is wat ik voorlopig heb:
<?php
class sng
{
public $data = array();
public $objects = array();
private static $instance;
public function __construct()
{
}
public function __clone()
{
throw new exception( "Cloning is not allowed" );
}
public static function singleton()
{
if( !isset( self::$instance ) )
{
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
public function registerClass( $key , $classname )
{
$this->objects[$key] = new $classname;
}
public function useClass( $key )
{
return $this->objects[$key];
}
public function putData( $value )
{
$this->data[] = $value;
return count($this->data)-1;
}
public function getData( $key )
{
if( is_numeric( $key ) )
{
return $this->data[$key];
}
else
{
throw new exception( "Key value is not valid (not an integer)" );
}
}
}
class testclass
{
public function somefunction()
{
echo "Foo Bar";
}
}
$test = sng::singleton();
$test->registerClass('tc','testclass');
$test->useClass('tc')->somefunction();
?>
<?php class sng { public $objects = array(); public function __construct() { } public function __clone() { throw new exception( "Cloning is not allowed" ); } public static function singleton () { if( !isset( self::$instance ) ) { $c = __CLASS__; self::$instance = new $c; } return self::$instance; } public function registerClass( $key , $classname ) { $this->objects[$key] = new $classname; } public function useClass( $key ) { return $this->objects[$key]; } public function putData( $value ) { $this->data[] = $value; return count($this->data)-1; } public function getData( $key ) { { return $this->data[$key]; } else { throw new exception( "Key value is not valid (not an integer)" ); } } } class testclass { public function somefunction() { } } $test = sng::singleton(); $test->registerClass('tc','testclass'); $test->useClass('tc')->somefunction(); ?>
Dit werkt allemaal.
allereerst: maak ik op de juiste manier gebruik van het singleton-principe (of hoe je dat ook noemt)?
En dan een de vraag:
ik zou graag willen dat ik functies van andere klasses op de volgende manier zou kunnen aanspreken:
$test = sng::singleton()->registerclass('tc','testclass')->useClass('tc');
$test->somefunction();
$test = sng::singleton()->registerclass('tc','testclass')->useClass('tc'); $test->somefunction();
op dit moment werkt die manier nog niet. Wat doe ik fout?
|