Creating classes with new and then referencing them with instance()

39 views
Skip to first unread message

Summer White

unread,
Feb 27, 2017, 11:31:17 PM2/27/17
to f3-fra...@googlegroups.com
I just ran across an interesting thing about calling a class directly vs calling it via its singleton instance.


class mytest extends prefab {

   
public $call_once = true;

   
function __construct() {

       
if ($this->call_once)
       
{
            $this
->call_once = false;
            echo
"I have not initizalized!<br>";
       
}
   
}
}

new mytest();

mytest
::instance();

Result

I have not initialized
I have
not initialized

That doesn't seem right?

It's not a big issue. But I had to change some very important code around.

new $module["module"]($module["namespace"]);

To

$module["module"]::instance($module["namespace"]);


I'm comfortable with dynamically creating a class since it is very standard but I'm not sure about dynamically calling it via Instance like this. Thoughts?


bcosca

unread,
Feb 28, 2017, 1:11:39 AM2/28/17
to f3-fra...@googlegroups.com
Singleton classes cannot and should not be instantiated through __construct. As such, __construct must be private.

Summer White

unread,
Mar 16, 2017, 1:54:57 AM3/16/17
to Fat-Free Framework
Ended up solving this in a better way for my application. My little module loader switches depending if the module is a prefab or not.


   
foreach ($f3->installed_modules as $module)
   
{
       
if (class_exists($module["module"]))
       
{
           
if (is_subclass_of($module["module"], "prefab"))
                $module
["module"]::instance();
           
else

               
new $module["module"]($module["namespace"]);
       
}
   
}
Reply all
Reply to author
Forward
0 new messages