Last active
February 10, 2017 12:47
-
-
Save kpion/6559e9a709ffdee9e2bddd90236cfa56 to your computer and use it in GitHub Desktop.
Why would we want to type hint variables via php doc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
Here is an example of type hinting variables (not function parameters), using php doc. | |
There is only one reason for doing this - to let IDEs know what is what. | |
*/ | |
class X{ | |
public function blahx(){ | |
echo 'blahx'; | |
} | |
} | |
class Y{ | |
public function blahy(){ | |
echo 'blahy'; | |
} | |
} | |
/** | |
* This func. will return instance of X or Y class, depending on the $what param. | |
*/ | |
function getMeSth($what){ | |
if($what == 'x'){ | |
return new X(); | |
} | |
if($what == 'y'){ | |
return new Y(); | |
} | |
throw new Exception('oh oh oh'); | |
} | |
/* | |
* getMeSth() will return instance of X or Y class depending on our decision in runtime. IDE have no idea, | |
* what it will actually return. So, no code completion support, but... | |
* thanks to the below lines, IDE knows what is the type of $sth - in this case, that is class X: | |
*/ | |
/** | |
*@var X $sth | |
*/ | |
$sth = getMeSth('x'); | |
//and we have code completion in most IDEs | |
$sth->blahx(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment