Email Updates RSS Subscribe
Line

This blog is created and maintained by the technical team at Hook in an effort to preserve and share the insights and experience gained during the research and testing phases of our development process. Often, much of this information is lost or hidden once a project is completed. These articles aim to revisit, expand and/or review the concepts that seem worth exploring further. The site also serves as a platform for releasing Flash tools developed internally to help streamline ad development.

Launch
Line

Hook is a digital production company that develops interactive content for industry leading agencies and their brands. For more information visit www.byhook.com.

Line

PHP Type Hinting with Eclipse

Line
Posted on August 11th, 2010 by Norm McGarry
Line

Are you a flash developer that occasionally has to dabble in php and hates the lack of strict typing and misses the ease of type-hinting like there is with actionscript? Well, any developer that is comfortable with Flex Builder will welcome Eclipse PHP Development Tools. Flex Builder, which is built on the Eclipse framework, functions almost identical to Eclipse with PDT. I’ve used Dreamweaver, Coda, Notepad++, jEdit, Komodo, PHP Designer — I’ve used almost all of them — to write PHP, and nothing is as powerful as Eclipse (in my opinion)! Plus, it is free! So, this is a post I’ve been meaning to write for a while and it should be short and sweet. There are a few features that took me a while to find that help greatly with writing PHP in Eclipse, so I thought I would document them here for those of you who wish they would have learned about these features years ago like I do.

Type Hinting

I’m an object-oriented coder that loves type-hinting. Type-hinting, if you aren’t familiar, is when the IDE automatically suggests variables and autocompletes your coding for you. In object-oriented coding, this is an amazing feature when accessing objects that contain many methods and variables.

Ctrl+Space (or Apple+Space)
Ctrl+Space is such an amazing key stroke. I potentially hit that key combination 1-3 times per line of code. Ctrl+Space will give you a drop-down window that prompts of suggestions to finish the variables or method you are typing out. It lists variable names, function/method names, data types to instantiate a new variable, as well as a list of all the built-in PHP functions. Simple, yet so beautiful.

Code Commenting

In a strict language like AS3, the IDE can just pick up on the type of a variable and handle code-hinting automatically. However, since PHP is a dynamically typed language, this isn’t the case. For example, methods and functions do not have a defined return type and it can be impossible for an IDE to know how to type a variable that gets it’s value from a method/function.

For example:

function someFunction($param)
{
 
	return "hello world";
}
 
$val = someFunction();

An IDE will have no idea how to type this value. However, with Eclipse, they have built in this amazing feature to handle that for you: code commenting. With a special syntax available in comments, you can define parameters with @param type $var_name, returns with @return type, and inline variables with @var $var_name type. This syntax based on PHPDocs and ASDocs and JDocs. For documentation on what is available, which seems to be right inline with Eclipse’s auto-complete features in every language, see this document: phpDocumentor tags.

/**
* My function description.
* 
* @param string $param
* @return string
*/
function someFunction($param)
{
 
	return $param . " world";
}
 
$val = someFunction("hello");

Now, when the IDE automatically will recognize that $val is a string. Obviously, not much type-hinting that can occur on a string, so let’s show a more complicated example.

 
/**
 * User
 */
class User
{
	/**
	 * Id for the user in the database
	 *
	 * @var int
	 */
	public $user_id;
	/**
	 * Name of the user.
	 *
	 * @var string
	 */
	public $user_name;
	/**
	 * email of the user
	 *
	 * @var string
	 */
	public $user_email;
	/**
	 * Role of the user
	 *
	 * @var Role
	 */
	public $role;
}
 
class Role
{
	/**
	 * Id of the role in the database.
	 *
	 * @var int
	 */
	public $role_id;
	/**
	 * Name of the role. (example is an administrator)
	 *
	 * @var string
	 */
	public $role_name = "Administrator";
}
 
class BlogEntry
{
	/**
	 * Author of the blog entry.
	 *
	 * @var User
	 */
	public $author;
	/**
	 * Publish date and time.
	 *
	 * @var DateTime
	 */
	public $publish_date_time;
	/**
	 * Title of the blog entry.
	 *
	 * @var string
	 */
	public $title;
	/**
	 * Body of the blog entry.
	 *
	 * @var string
	 */
	public $body;
	/**
	 * Populates the variables.
	 *
	 * @param string $title
	 * @param string $body
	 * @param User $author
	 * @param DateTime $date_time
	 */
	public function populate($title, $body, $author, $date_time)
	{
		$this->title = $title;
		$this->body = $body;
		$this->author = $author;
		$this->publish_date_time;
	}
}

Now, the IDE will automatically type the following code with ease:

$user = new User();
$user->user_id = 1;
$user->user_name = "Norm";
$blogEntry = new BlogEntry();
$blogEntry->populate('sample title', 'sample body', $user, new DateTime());
echo($blogEntry->date_time->format("Y-m-d H:i:s"));
echo($blogEntry->author->user_name);

The IDE will automatically display a drop-down milliseconds after you type “->” on the objects with a suggestion of variables and methods in the DateTime and User objects. This feature is amazing when you are dealing with hundreds of objects. It highly reduces the time spent looking through documentation to figure out variable names in an object.

Inline Typing

Most of that is pretty obvious and is pretty easy to manage, but there were certain scenarios where I did not know how to get the type hinting to work. For example, a loop!

$me = new User('Norm','norm@byhook.com',new Role("Administrator"));
$client = new User("John Doe","hello@byhook.com",new Role("client"));
$users = array($me, $client);
 
foreach($users as $user)
{
	echo($user->user_name . " - " . $user->role->role_name . "\n");
}

In this situation, the IDE wont know how to type the $user variable in the loop, because it does not know the type of the contents in the $users array. Thankfully, we can type variables inline inside the code. We simply add the following to our loop:

/* @var $user User */
foreach($users as $user)
{
	echo($user->user_name . " - " . $user->role->role_name . "\n");
}

Now, the IDE will automatically recognize the $user variable as being of the type User.

It is possible to have one function/method return multiple types and that CAN be a very convenient feature, but again, I like to be strict in my typing and I love code-hinting too much to do this. I personally don’t like to switch from a string to an integer to an object on one variable, even though PHP allows it. I prefer code that is easy to understand and highly reusable. However, it is just a matter of opinion! Hope it helped!

Line
Facebook TwitThis Digg Reddit StumbleUpon del.icio.us
31 Responses to “PHP Type Hinting with Eclipse”
  1. [...] peuvent être obtenues dans d’autres contextes également, je vous invite à découvrir le poste qui m’a permis de trouver cette info pour approfondir le sujet [...]

  2. ZCWYLNDSYHNBY
    Welcome to Oakley Sunglasses Hut to buy cool and cheap oakleys sunglasses.

  3. As I website possessor I conceive the content here is very fantastic , thankyou for your efforts.

  4. Nice post! , thanks the admin give the userful article! come on to my store have a look! I very like.
    Welcome to our store online: http://www.cheapshoes-handbags.us We selling all kind of Cheap Nike Shoes, Wholesale Jordan Shoes, Cheap LV handbags,Discount Handbags,high quality, low price!

  5. Thank you for sharing, this information is useful to me. good quality
    Welcome to our store online: http://www.cheapjerseys-sale.com.
    Cheap NFL Jerseys, NHL Jerseys, MLB Jerseys, Cheap Jerseys Sale from China, off 68%,All name and number are sewn on!

  6. Wow, this is very interesting to read.
    Do you like Cheap Nike Shoes, We selling all kind of High quality Cheap Nike Shoes,Cheap Nike Shox Shoes,Wholesale Air Max Shoes, Cheap Nike Trainers,Cheap Nike Duck Shoes from China, fashion and cheap!

  7. Thank you, your point of view is very good!
    Welcome to our store: http://www.cheapcosmetics-wholesale.com
    We selling all kind of High quality Cheap MAC Makeup,Discount MAC Cosmetics, Mac Makeup Wholesale, Cosmetics Wholesale, We are larger factory to Nike Shoes, Lowest Price! Top Quality!

  8. Wind, blown crystal snowflake Solitude, tods shoes uk,tods shoes uk bleak memory, custom jerseys,custom jerseys because you and warm. Merry Christmas.

  9. Very helpful information. Very helpful, great share.

  10. 85-86 season, the Rockets franchise history at its peak in the ranks, though soon they fall apart on their own. Finals in 86 years up to 18 months after the suspension period, the Rockets the best three defenders Lucas, Lloyd and Wiggins were caught in a drug abuse problems, breaking again to the championship of the rocket impact of hope. 86-87 season the Rockets get 42-20, Western group ranked third, unknown into the playoffs.

  11. These fashion-forward UGG Mayfaire boots total any casual look.With amulti-colored zipper along the side of the boot,the Mayfaire takes a basicsilhouette to some fresh, style forward style.A metal logo plate adds signaturedetail for the heel.A multi-tonal zipper provides effortless suit in the side of the 8inch shaft. moisture-wicking sheepskin cushioninginsole regulates temperatures in warm and cold climates.

  12. NHL jerseys says:

    Thanks a lot for sharing this amazing knowledge with us. This site is fantastic. I always find great knowledge from it.

  13. Loomis mentioned the top workplace was self-confident Payton wished to sustain what he has assisted develop in New Orleans instead than start much more than somewhere else yangchengbin/201112

  14. NFL Hats says:

    His times using the Bears started to be numbered using the signing of Marion Barber, and any attempts to business him went nowhere.
    To make room, the Cardinals released tight complete Stephen Spach, linebacker Quan Sturdivant and defensive complete Ronald Taley. Taylor, who turns 32 on Sept. 22, passed his actual on Monday,-5″ but do not exercise using the team. He is anticipated to participate in Wednesday’s workout and be available when Arizona opens its time period Sunday at house against the Carolina Panthers.yangchengbin/201112

  15. Thank you for sharing, this information is useful to me. good quality

  16. beats by dre says:

    Hi, I’m learning new Dreamweaver would be very helpful for me thanks

  17. beats dr dre says:

    Thank you for taking the time to publish this information very useful!I’m still waiting for some interesting thoughts from your side in your next post thanks.

  18. XHPJOYQCC1F5HTFWXZ
    all types of UGG boots for women and men to enjoy their life time

  19. Thank you for sharing your stuff on blog. It is doubtless that we have similar interests. Something are very helpful to me.

  20. Jerseys says:

    I am pretty much pleased with your good work.You put really very helpful information. Keep it up. Keep blogging. Looking to reading your next post.

  21. Thank you for taking the time to publish this information very useful!
    http://www.pandorabracelets2u.org/ Pandora jewellery

  22. 2011NFL says:

    http://www.buycheapcanadegoose.com/ it is a good article for us ,i have been find everywhere for this kind of point ,and now i find ,tks for the ownner to shar this kinds of article with us .tks so much.by the way ,i have some idear to share with every boday too.Canada Goose Freestyle Vestfor the inner of the dwon jackets ,there is duck downs inside ,it is very nice to keep warm for urself.which one is the best winter down jackets or down coat,pls see our link ,then u will see.yangchenbin/201110

  23. Im a sucker for your blog post! do you set up this valuable one self or alternatively have you use outside agencies for the application? Instant messaging looking to purchase a web log style and design that’s exactly very much the same which means that that’s exactly really the only good reason Instant messaging wanting to know. You ultimately choose keep up to date the favorable deliver the results

  24. Our company supply all kinds of Nlf shirt with cheap price, you can save up to 60%. If you are an amateur or literlly play, wearing a football jersey on the body, you will be more like sports to bring you pleasure. Often in the position and team sporting a status symbol, precisely because of this, the campaign has been selected not only for the U.S. shirt the shirt itself, the campaign’s position to reflect a symbol of glory ! who is your favorite d team, they like the same strategy for the glory of your own idol! Welcome to our store to buy a cheap shirt. Click http://www.cheapjerseyscustom.com /Desean-Jackson-Jersey-Philadelphia-Eagles-10-White-Jersey-974.html

  25. özel says:

    good code stream

  26. Tim says:

    Hi

    sorry for the quick comment, just find a solution.
    I need to “add PHP support”. (my project is not a native PHP project)

    thanx

  27. Tim says:

    Hi,

    Thanks for the post.
    But It doesn’t work for me now. I’m using the latest Eclipse Helios version with PDT 2.2.

    is there any additional setting for this?

  28. good post php and Dreamweaver

  29. Hi, I’m learning new Dreamweaver would be very helpful for me thanks

  30. [...] This post was mentioned on Twitter by tony murphy, Norm McGarry. Norm McGarry said: New blog entry – PHP Type Hinting with Eclipse – Check it out! http://bit.ly/aliBJi [...]


Leave a Reply

*

Line
Line
Pony