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 Construct
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;
}
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).
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.
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_tags.return.pkg.html
For future reference, this is implemented for PHP 7, with the following syntax (quoted from source):
function foo(): array {
return [];
}
To answer your question now, as of PHP 7 (released around end of 2015) you will be able to do the following (as an example):
<?php
function ConstructPDOObject($hostname, $dbname, $username, $password): PDO
{
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
return $dbh;
}
The specification also allows for type hinting within and against interfaces; for those of us interested in adhering to SOLID principles.
Source and more information: https://wiki.php.net/rfc/return_types