tags:

views:

707

answers:

4

What is the correct syntax for me to specify the return type hints for a method?

For example, I have such a method:

private static function ConstructPDOObject($dbname) 
{
   $hostname =self::HOSTNAME;
  $username = self::USERNAME;
  $password = self::PASSWORD;
  $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
  return $dbh;
}

And I want, whenever I call the above method, the IDE will show me the methods for PDO.

How to add the type hint?

+1  A: 

PHP doesn't support type hinting on return types. Perhaps you should add a documentation block declaring the return type and maybe your IDE will pick that up (I don't know if it will or not).

cletus
+1  A: 

Return type hints are only supplied by your IDE. Zend studio and PDT support the PHPDocumentor style doc blocks.

http://manual.phpdoc.org/HTMLSmartyConverter/PHP/phpDocumentor/tutorial%5Ftags.return.pkg.html

Mark F
+2  A: 

The IDE hinting is done via comments. Here is an example from one of my ZEND Front Plugins.

<?php

/**
 * Initializes Application wide authentication
 *
 * @author Lance Rushing
 * @since  2009-06-01
 * @param  Zend_Session $session
 * @return Zend_Auth  <--- gives IDE Hint
 */
protected function initAuth($session)
{
    $auth = Zend_Auth::getInstance();
    require_once 'AuthStorage.php';
    $auth->setStorage(new My_AuthStorage($session));
    return $auth;
}
Lance Rushing
+2  A: 

Within Aptana, PDT, Zend Studio and other IDE's you can add type hinting to php methods as follows:

/**
 * Constructs a new PDO Object and returns it
 *
 * @param string $dbname name of the database to connect to
 * @return PDO connection to the database
 */
private static function ConstructPDOObject($dbname) 
{
      $hostname =self::HOSTNAME;
            $username = self::USERNAME;
            $password = self::PASSWORD;
            $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
            return $dbh;
}

The class name is placed after the @return attribute of the documentation block to signify the return type of the method. E.g. In the case of your example method, PDO is the class name that is returned. The additional description "connection to the database" is used to provide a meaningful description of the returned value to other developers, this is not required but is advised.

One of the great things about documenting your php methods in this manner, is that you can then generate documentation using either phpDocumentor or doxygen.

Josiah