note 100209 added to language.oop5
| From: | DavMe at osu1 dot php dot net | Date: | Fri, 01 Oct 2010 07:03:43 +0000 |
| Subject: | note 100209 added to language.oop5 | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-172864@lists.php.net to get a copy of this message | ||
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!
----
Server IP: 69.147.83.197
Probable Submitter: 99.22.215.240
----
Manual Page -- http://www.php.net/manual/en/language.oop5.php
Edit -- https://master.php.net/note/edit/100209
Del: integrated -- https://master.php.net/note/delete/100209/integrated
Del: useless -- https://master.php.net/note/delete/100209/useless
Del: bad code -- https://master.php.net/note/delete/100209/bad+code
Del: spam -- https://master.php.net/note/delete/100209/spam
Del: non-english -- https://master.php.net/note/delete/100209/non-english
Del: in docs -- https://master.php.net/note/delete/100209/in+docs
Del: other reasons-- https://master.php.net/note/delete/100209
Reject -- https://master.php.net/note/reject/100209
Search -- https://master.php.net/manage/user-notes.php