views:

461

answers:

2

Take the following code as an example:

class xpto
{
    public function __get($key)
    {
     return $key;
    }
}

function xpto()
{
    static $instance = null;

    if (is_null($instance) === true)
    {
     $instance = new xpto();
    }

    return $instance;
}

echo xpto()->haha; // returns "haha"

Now, I'm trying to archive the same result but without have to write the xpto class. My guess is I should have to write something like this:

function xpto()
{
    static $instance = null;

    if (is_null($instance) === true)
    {
     $instance = new stdClass();
    }

    return $instance;
}

echo xpto()->haha; // doesn't work - obviously

Now, is it possible to add __get() magic functionality to the stdClass object? I guess not, but I'm not sure.

+2  A: 

No, it is not possible. You cannot add anything to stdClass. Also, unlike Java, where every object is a direct or indirect subclass of Object, this is not the case in PHP.

class A {};

$a = new A();

var_dump($a instanceof stdClass); // will return false

What are you really trying to achieve? Your question sounds a bit like "I want to close the door of my car, but without having a car" :-).

Cassy
Thanks Cassy, I thought there might be an obscure way to create some sort of lambda classes but I guess not. Thank you for your input. =)
Alix Axel
+1  A: 

The OP looks like they are trying to achieve a singleton pattern using a function in the global scope which is probably not the correct way to go, but anyway, regarding Cassy's answer, "You cannot add anything to stdClass" - this is not true.

You can add properties to the stdClass simply by assigning a value to them:

$obj = new stdClass();
$obj->myProp = 'Hello Property';  // Adds the public property 'myProp'
echo $obj->myProp;

However, I think you need PHP 5.3+ in order to add methods (anonymous functions / closures), in which case you might be able to do:

$obj = new stdClass();
$obj->myMethod = function($name) {echo 'Hello '.$name;};
$obj->myMethod('World');  // Output: Hello World

However, I've not tried this. But if this does work, can you do the same with the magic __get() method? Which is what I was wanting to do as well and how I found this thread (although, alas, I am currently on PHP 5.2.9 so no closure for me!)

w3d