Search code examples
phpeclipseoopeclipse-pdtcode-completion

Eclipse PDT word completion fails for PHP singleton instances


I have a basic singleton class, similar to the one shown in the PHP documentation:

// Based on "Example #2 Singleton Function" from
// www.php.net/manual/en/language.oop5.patterns.php
class Example {
    private static $instance;

    private function __construct() {
        echo 'I am constructed';
    }

    public static function singleton() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }

    public function myMethod() {
        echo 'This is my method';
    }
}

The code I write to get an instance of this class is:

$myExample = Example::singleton();

Using PDT, if I try to use its word completion to find the method myMethod in this instance, it fails. That is, if I type the following in the editor:

$myExample->

And immediately after the "->", I press the key combination for word completion (Ctrl+Space on my computer), Eclipse tells me "No Default Proposals". I expect to see "myMethod" appear as a choice, but it doesn't.

How can I make word completion work? Do I need to configure Eclipse differently? Do I need to write my singleton a different way?


Solution

  • Comments are your friend

    /**
    *
    * @return Example
    */
    public static function singleton() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }
        return self::$instance;
    }
    

    Add the @return annotation to the method docblock and eclipse should recognize that and provide detailed auto-complete choices.