note 100209 deleted from language.oop5 by googleguy

From: Date: Wed, 16 Jan 2013 05:37:45 +0000
Subject: note 100209 deleted from language.oop5 by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-193105@lists.php.net to get a copy of this message
Note Submitter: DavMe ---- When you have a class name in a variable and want to create a new instance of that class, you can simply use: <?php $className = "ClassName"; $instance = new $className(); ?> If, however, you have a class that is part of a singleton pattern where you cannot create it with new and need to use: <?php $instance = ClassName::GetInstance(); ?> ...you quickly discover that it fails miserably with a variable. Fail Example: <?php $className = "ClassName"; $instance = $className::GetInstance(); ?> After a few days of head pounding, I finally put together this workaround: <?php $className = "ClassName"; eval('$instance = '.$className.'::GetInstance();'); ?> I hope this saves you some effort and if anyone knows of a non-eval method to accomplish this, please share! Thanks!

« previous php.notes (#193105) next »