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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With