Distortion To Static


The life, times and ramblings of MasterCJ
http://bugs.php.net/bug.php?id=51083 << this is shit.

<?php

class Foo {
function __construct() {
$this->Bar = function() {
echo 'Hello, world!';
};
}
}

$Foo = new Foo();
$Foo->Bar();

?>


Expected result:
----------------
Hello, world!

Actual result:
--------------
PHP Fatal error: Call to undefined method Foo::Bar()


Turns out that it is kind of doable, but definitely not in a nice way.

<?php

$Foo = new Foo();
$Bar = $Foo->Bar;
$Bar();

?>


I had planned to use anonymous functions for factories in a simple application, but noooo. I had planned to have a __call() function that caught all get*() and set*() functions and acted on an array, in a simple singleton wrapper kind of thing. I had then planned to, instead of actually populating the object, just put a function that created whatever I wanted it to return, put it into the singleton wrapper, then returned it. This way I could do things like...

<?php

Manager::getInstance()->setPDO(function() {
$PDO = new PDO('sqlite://./database.db');
Manager::getInstance()->setPDO($PDO);
return $PDO;
});
$PDO = getPDO();

?>


...and only create the PDO object at the last second. This would mean that after all the caches had warmed up for the associated objects that require data, some page loads could completely avoid creating the PDO object. This also applies to things like mailer abstraction classes, templaters, etc.

IT WOULD HAVE BEEN BEAUTIFUL.

Now I have some code in the manager class like this:

<?php
if (is_a($this->Objects[$Object], 'Closure')) {
$this->Objects[$Object] = $this->Objects[$Object]->__invoke();
}
?>


Kind of ew, hey?
permalink 1 comment
Comment by noiz @ 05/07/10 02:29 pm
sif use anonymous functions within static defined class.