1

Is there a function in php that will return any instance of class available in memory?

Its direct complement would be class_exists.

if( class_exists($className)){ 
    $className = get_class($instance); // returns well.. you know.
}

// imaginary functions

instance_exists($className);
get_instance($className); // returns any instance it can find.

I don't have a case scenario were it can be useful. But it can find use in applications which provide some form of plugin system where plugins just implement interfaces and have the application just shift between implementations.

  • Only if that variable is either static or in the current scope. You can use if($instance != null) .... – Niek van der Maaden May 09 '17 at 06:54
  • [`class_exists()`](http://php.net/manual/en/function.class-exists.php) does not accept as argument an instance but a class name. To answer your question: No, such a function does not exist. – axiac May 09 '17 at 08:40
  • @axiac yeah small visual typo there. variable may contain string class name though :-). thanks for the catch. – Cholthi Paul Ttiopic May 09 '17 at 08:43
  • 1
    As far as I understand you're looking for the singleton pattern, which you can learn about here: http://stackoverflow.com/a/203359/4461980 – Florian Humblot May 09 '17 at 08:44
  • @FMashiro the Singleton, as implemented in the answer you linked to, is an [anti-pattern](https://en.wikipedia.org/wiki/Singleton_pattern). – axiac May 09 '17 at 08:49
  • @axiac the question wasn't about whether it was a pattern or an anti-pattern, the asker is really just asking for a singleton, where you only have one instance of a class in memory. The entire pattern vs anti-pattern discussion is not the point of this discussion – Florian Humblot May 09 '17 at 08:51
  • You can only search for instances in global namespace, or use service locator pattern. – Danijel May 09 '17 at 08:56
  • @Danijel how do you search for instances in global namspaces – Cholthi Paul Ttiopic May 09 '17 at 12:21
  • By searching through [`$GLOBALS`](http://php.net/manual/en/reserved.variables.globals.php) or [`get_defined_vars()`](http://php.net/manual/en/function.get-defined-vars.php) arrays. – Danijel May 09 '17 at 12:34
  • @Danijel are you saying no instance will be in memory if not present in $GLOBALS or get_defined_vars(). I was about to ask, what if we didn't have a reference at hand. Now I got it. – Cholthi Paul Ttiopic May 09 '17 at 13:04

0 Answers0