I have an extended class with an overriden method doSomething().
For some reason the inherited class' method never runs only the base one.
class cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClass();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something';
}
public function call_me() {
$this->doSomething();
}
}
class cDemoClassEx extends cDemoClass {
protected function doSomething() {
echo 'do something differently';
}
}
$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();
result:
do something
do something
The second one should be "do something differently" at least that's what I'm expecting.
Can anyone tell me what I'm doing wrong? Thanks
In this case, you need using late static binding (5.3+). Change in parent method getInstance line :
$instance = new cDemoClass();
to
$instance = new static();
You will get:
do something
do something differently
Read more about this feature here: http://www.php.net/manual/en/language.oop5.late-static-bindings.php
Because cDemoClassEx::getInstance(); is still returning new cDemoClass();. You have to also overwrite the getInstance() method:
class cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClass();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something';
}
public function call_me() {
$this->doSomething();
}
}
class cDemoClassEx extends cDemoClass {
public static function getInstance() {
static $instance = null;
if ($instance === null)
$instance = new cDemoClassEx();
return $instance;
}
private function __construct() {
}
protected function doSomething() {
echo 'do something differently';
}
}
$baseclass = cDemoClass::getInstance();
$baseclass->call_me();
echo '<br/>';
$extendedclass = cDemoClassEx::getInstance();
$extendedclass->call_me();
You have to override with the cDemoClassEx::getInstance() and change this line
$instance = new cDemoClass();
into
$instance = new cDemoClassEx();
You will also need to declare the cDemoClass::__construct() as protected or simply override it in cDemoClassEx.
Related
Trying to use objects that extend singletone, but something I can't do.
How to call method from extended class?
How to show 13 non 12 with singleton?
class SingletonTest
{
protected static $_instance;
private function __construct(){}
private function __clone(){}
public static function getInstance() {
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //12
You will get what you want if you use static binding keyword "static" instead of "self"
class SingletonTest
{
protected static $_instance;
private function __construct(){}
private function __clone(){}
public static function getInstance() {
if (null === static::$_instance) {
static::$_instance = new static();
}
return static::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //13
$a = SingletonTest::getInstance();
echo $a->test2(); //13
exit;
But as You see in the above example this way a class which You will call first to "getInstance" will take place to store its instance in the $_instance field.
There is no way to create a base singleton class and inherit singleton behavior.
public static function getInstance()
{
static $instances = array();
$calledClass = get_called_class();
if (!isset($instances[$calledClass]))
{
$instances[$calledClass] = new $calledClass();
}
return $instances[$calledClass];
}
So this should work for you:
(So first normally functions are public so you can use them if you extend from another class! And the you have to make an object from ExtendSingleton not from SingletonTest since ExtendSingleton exdend's -> SingletonTest and not the other way.)
<?php
class SingletonTest {
protected static $_instance;
public function __construct() {
}
public function __clone() {
}
public static function getInstance() {
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest {
public function test2() {
return 13;
}
}
$b = new ExtendSingleton();
echo $b->test2(); //13
?>
Output:
13
I've tested bicccio's solution and it works
class SingletonTest
{
protected static $_instances = [];
private function __construct(){}
private function __clone(){}
public static function getInstance()
{
$calledClass = get_called_class();
if (!isset(self::$_instances[$calledClass]))
{
self::$_instances[$calledClass] = new $calledClass();
}
return self::$_instances[$calledClass];
}
public function test2(){
return 12;
}
}
class ExtendSingleton extends SingletonTest
{
public function test2() {
return 13;
}
}
$b = ExtendSingleton::getInstance();
echo $b->test2(); //13
$a = SingletonTest::getInstance();
echo $a->test2(); //12
You can extend singleton class in php using late static binding the whole process is well discussed in this question.
Creating the Singleton design pattern in PHP5
in this below class i want to use class like with static methods and for use class methods without create new object from parent.
for example:
<?php
class Permission
{
protected $permission = false;
protected $id = 0;
public static function __construct()
{
return new static;
}
public function user( $id )
{
$this->id = $id;
}
public function check()
{
$this->permission = true;
}
public function item( $item )
{
return $item;
}
}
$bar = Permission::user(100)->item("HELLO");
print_r($bar);
this code not working and have problem. how to resolve this class problem?
That will not work because user method is not static, try changing this two methods, and this is good way of generating objects
public function __construct($id)
{
$this->id = $id;
}
public static function user( $id )
{
return new static($id);
}
I'd suggest you a singleton pattern, like this
class Permission
{
static protected $permission = false;
static protected $id = 0;
private static $_instance = null;
private function __construct () { }
public static function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self;
}
return self::$_instance;
}
public static function user( $userId )
{
self::$id = $userId;
return self::$_instance;
}
public static function check()
{
self::$permission = true;
return self::$_instance;
}
public static function item( $item )
{
return $item;
}
}
$bar = Permission::getInstance()->user(100)->item("HELLO");
print_r($bar);
You can chain methods in 'dynamic' classes by returning $this at the end of method (remember, you have a static).
class A {
public function someMethod()
{
// some code
return $this
}
public function otherMethod()
{
// some code
return $this
}
$a = new A();
$a->someMethod()->otherMethod();
}
There is a public library, and there is a class that can have only one instance in one PHP process, so it's Singleton. The problem is that initialization of this class require some configuration arguments and I can't find good issue to pass them in class constructor.
The only issue I found is:
public static function init($params) {
if(self::$instance) {
throw new Exception(__CLASS__ . ' already initialized');
}
$class = __CLASS__;
self::$instance = new $class($params);
}
public static function getInstance() {
if(!self::$instance) {
throw new Exception(__CLASS__ . ' is not initialized');
}
return self::$instance;
}
But I don't think that it's so really good.Is there any other ideas?
Thanks!
There is example of bad, but working issue:
if(!defined('PSEOUDSINGLETON_PARAM')) {
define('PSEOUDSINGLETON_PARAM', 'default value');
}
class PseoudoSingleton {
protected function __construct($param1 = PSEOUDSINGLETON_PARAM) {
// ...
}
public static function getInstance() {
if(!self::$instance) {
$class = __CLASS__;
self::$instance = new $class();
}
return self::$instance;
}
}
/* on library/utility level */
class nonSingletonService { public function __construct($options){} }
/* on application logic level, so, knows all context */
function getSingleton(){
static $inst;
if (!$inst) $inst=new nonSingletonService(calculateParameters());
return $inst;
}
Sample Singleton implementation:
class MySingleton
{
private static $_INSTANCE = null;
private function __construct()
{
// put initialization code here
}
public static function getInstance()
{
if(self::$_INSTANCE === null) self::$_INSTANCE = new MySingleton();
return self::$_INSTANCE;
}
}
Note that constructor is private, so it can only be called from the class itself.
References to the instance can be only obtained by getInstance call, which creates the object on first call, any subsequent calls will return references to an existing object.
Why are you checking it twice?
Just do the following:
private static function init($params) {
$class = __CLASS__;
self::$instance = new $class($params);
}
public static function getInstance($params) {
if(!self::$instance) {
self::init($params);
}
return self::$instance;
}
That way, you know that you only need to check once and you know you only call init() if the instance is not initialized.
We have a class that holds a public array called $saved that contains lots of data required to share between methods (example below)...
class Common {
public $saved = array();
public function setUser($data) {
$this->saved['user_data'] = $data;
}
public function getUserID() {
return $this->saved['user_data']['id'];
}
}
There are literally thousands of lines of code that work like this.
The problem is that new instance of classes that extend Common are being made within some methods so when they access $saved it does not hold the same data.
The solution is to make $saved a static variable, however I can't change all of the references to $this->saved so I want to try and keep the code identical but make it act static.
Here is my attempt to make $this->saved calls static...
class PropertyTest {
private $data = array();
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
return null;
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
}
class Common {
public $saved;
private static $_instance;
public function __construct() {
$this->saved = self::getInstance();
}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new PropertyTest();
self::$_instance->foo = array();
}
return self::$_instance->foo;
}
}
This doesn't quite work when setting a variable it doesn't seem to stay static (test case below)...
class Template extends Common {
public function __construct() {
parent::__construct();
$this->saved['user_data'] = array('name' => 'bob');
$user = new User();
}
}
class User extends Common {
public function __construct() {
parent::__construct();
$this->saved['user_data']['name'] .= " rocks!";
$this->saved['user_data']['id'] = array(400, 10, 20);
}
}
$tpl = new Template();
print_r($tpl->saved['user_data']);
$this->saved is empty when User gets initialized and doesn't seem to be the same variable, the final print_r only shows an array of name => bob.
Any ideas?
First of all, I have to say that, IMO, it is not that good to use an instance's property as a class's property ($saved is not declared as static but its value is shared with all instance).
Here is a working version http://codepad.org/8hj1MOCT, and here is the commented code. Basically, the trick is located in using both ArrayAccess interface and the singleton pattern.
class Accumulator implements ArrayAccess {
private $container = array();
private static $instance = null;
private function __construct() {
}
public function getInstance() {
if( self::$instance === null ) {
self::$instance = new self();
}
return self::$instance;
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
class Common {
public $saved = null;
public function __construct() {
// initialize the "saved" object's property with the singleton
// that variable can be used with the array syntax thanks to the ArrayAccess interface
// so you won't have to modify your actual code
// but also, since it's an object, this local "$this->saved" is a reference to the singleton object
// so any change made to "$this->saved" is in reality made into the Accumulator::$instance variable
$this->saved = Accumulator::getInstance();
}
public function setUser($data) {
$this->saved['user_data'] = $data;
}
public function getUser() {
return $this->saved['user_data'];
}
}
class Template extends Common {
// you can redeclare the variable or not. Since the property is inherited, IMO you should not redeclare it, but it works in both cases
// public $saved = null;
public function __construct() {
// maybe we can move this initialization in a method in the parent class and call that method here
$this->saved = Accumulator::getInstance();
}
}
I think there are a number of issues with this implementation that could well come back to bite you. However, in your current implementation your contructing a new instance (albeit through a static call) every time.
Instead use getInstance() as your singleton hook, and make your __construct private, as you'll only be accessing it from with the context of the Common class.
Like so:
class Common {
public $saved;
private static $_instance;
private function __construct() {
}
public static function getInstance() {
if (self::$_instance === null) {
self::$_instance = new self();
... any other modifications you want to make ....
}
return self::$_instance;
}
}
And don't ever run parent::_construct(), instead always use the getInstance() method.
You might also want to ditch the idea of extending this singleton class. This is really a bad antipattern and could cost you a number of issues in the long run. Instead just maintain a Common class that other classes can read / write to. As its a singleton you don't need to worry about injection.
I seem to have solved the problem, by making $this->saved a reference to a static variable it works...
class Common {
private static $savedData = array();
public $saved;
public function __construct() {
$this->saved =& self::$savedData;
}
}
I'm a AS3 coder and i do a bit of php and i am having a hard time doing a static class that can cache variables.
Here's what i have so far :
<?php
class Cache {
private static $obj;
public static function getInstance() {
if (is_null(self::$obj)){
$obj = new stdClass();
}
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
public static function set($key,$value){
self::$obj->$key = $value;
}
public static function get($key){
return self::$obj->$key;
}
}
?>
And i use the following to set my variable into an object of my static class :
<?php
include 'cache.php';
$cache = new Cache();
$cache->set("foo", "bar");
?>
And this is retrieve the variable
<?php
include 'cache.php';
$cache = new Cache();
$echo = $cache->get("foo");
echo $echo //doesn't echo anything
?>
What am i doing wrong ? Thank you
I've adapted #prodigitalson's code above to get something rudimentary that works (and has much room for improvement):
class VarCache {
protected static $instance;
protected static $data = array();
protected function __construct() {}
public static function getInstance() {
if(!self::$instance) {
self:$instance = new self();
}
return self::$instance;
}
public function get($key) {
self::getInstance();
return isset(self::$data[$key]) ? self::$data[$key] : null;
}
public function set($key, $value) {
self::getInstance();
self::$data[$key] = $value;
}
}
Usage
VarCache::set('foo', 'bar');
echo VarCache::get('foo');
// 'bar'
You'll want this class to be available everywhere you need it, and if you want it to persist between requests, I'd consider using Memcached or something similar, which will give you everything you need.
You could alternatively use some SPL functions, like ArrayObject, if you wanted to be clever :)
Try this:
class VarCache {
protected $instance;
protected $data = array();
protected __construct() {}
public static function getInstance()
{
if(!self::$instance) {
self:$instance = new self();
}
return self::$instance;
}
public function __get($key) {
return isset($this->data[$key]) ? $this->data[$key] : null;
}
public function __set($key, $value) {
$this->data[$key] = $value;
}
}
// usage
VarCache::getInstance()->theKey = 'somevalue';
echo VarCache::getInstance()->theKey;