Last active
August 29, 2015 14:07
-
-
Save orolyn/9ff0756b3cb3cdfe454b to your computer and use it in GitHub Desktop.
Concept of custom type hints
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 | |
/** | |
* The typehint definition requires an implementation of ::evaluate. | |
* It accepts a reference to a value as an argument. | |
* From here an assertion can be performed, or the value can be modified. | |
* | |
* The visibility of the method and whether it is static or not may be irrelevant. | |
*/ | |
typehint Int | |
{ | |
function evaluate(&$value) { | |
if (!is_int($value)) { | |
throw new InvalidArgumentException('Expected an integer'); | |
} | |
} | |
} | |
/** | |
* A more semantically accurate implementation may take place directly inside the body | |
* of the declaration. | |
* | |
* The variable &$value already being exposed. | |
*/ | |
typehint Int | |
{ | |
if (!is_int($value)) { | |
throw new InvalidArgumentException('Expected an integer'); | |
} | |
} | |
/** | |
* Example without typehint. | |
* | |
* In this example, the argument is validated in the body of the method. | |
*/ | |
class A | |
{ | |
public function test($value) | |
{ | |
if (!is_int($value)) { | |
throw new InvalidArgumentException('Expected an integer'); | |
} | |
// ... | |
} | |
} | |
/** | |
* Example with typehint. | |
* | |
* In this example, the argument is validated by the type hint. | |
*/ | |
class A | |
{ | |
public function test(Int $value) | |
{ | |
// ... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment