Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
<?php
highlight_file(__FILE__);
class base
{
public static $name = 'base';
function &staticInstance()
{
static $instance;
if(!isset($instance)){
$instance = & new self::$name;
}
return $instance;
}
}
class test extends base
{
var $num = 0;
public static $name = 'test';
function num($num)
{
$this->num += $num;
echo $num;
}
}
$a = test::staticInstance();
var_dump($a);
$a->num(3);
?>
Now, you would expect a output like '3'.
But! The function makes a base class, instead of a test class.
So you get a fetal error, that the num function doesnt exists.
Any idee's about how you can make a singleton function work in this setup?
Seriously - You don't need static members. Just instantiate the class, when needed. If you have to reuse the instance in multiple places in your code, there are much better ways, than using a Singleton.
Oops, I meant to say "I have not found a good explanation as to why however."
There have been several threads here where we've talked about singletons and their overuse. Some may be in the moderhood instead of "public;" I can't recall those specifics.
feyd wrote:Oops, I meant to say "I have not found a good explanation as to why however."
There have been several threads here where we've talked about singletons and their overuse. Some may be in the moderhood instead of "public;" I can't recall those specifics.
No prob. I found a thread at Sitepoint that was pretty good.
PHP's implementation of static functions and members is broken. Static methods do not inherent there context. They always belong to the class in which they are defined. This makes them nothing more than functions with a funky name. There are a number of design patters that are simply not easily reproducible using PHP because of this.
So far the PHP developers view this as the intended behavior and have been unwilling to rectify.