Wednesday 13 July 2011

PHP autocomplete / code assist in Eclipse

I've been programming in PHP a lot recently, and the main issue I've been having is that Eclipse finds it difficult to auto-complete e.g. suggest methods that can be run on an instance of a class. This article shows you how to fix this using PHPDoc to give Eclipse more type information. Note: it assumes you have a User class on your include_path.

You can declare types for arguments to functions. Note: ignore the double spacing - it is a bug with the FogBugz wiki
function myFunction(User $user) {
$user-> // this will now autocomplete
}

You can declare return type of functions
/** @return User */
private function getUser() {
return new User();
}

public function run() {
$user = $this->getUser();
$user-> // this will now autocomplete
}

You can declare the type of class properties (AKA fields), accessed with $this->var. Note: you can also do this inline above the property itself, using @var instead of @property, BUT annoyingly the PHPdoc has to be in the 3 line form (doesn't work if you shorten it to 1 line e.g. /** @var User $user */)
/**
* @property User $user
*/
class myClass {
protected $user;
function myFunction() {
$this->user-> // this will now autocomplete
}
}

You can declare the type on variables in the code
/* @var $user User */
$user-> // this will now autocomplete

2 comments:

  1. great! I looked long time for the
    /**
    * @property User $user
    */
    thanks!!

    ReplyDelete
  2. Kerry McCullough20 June 2012 at 22:19

    Thanks! It was this part that I didn't know about that was driving mad until you pointed it out!

    /* @var $user User */$user-> // this will now autocomplete
     

    ReplyDelete