Last active
December 22, 2015 23:58
-
-
Save pdewouters/6550033 to your computer and use it in GitHub Desktop.
In this case, we remove the type hinting, leaving a default value of an empty array.
If another type is passed, the code may not fail but will cause unexpected results. Notice the extra if statements I added in the processing function to check if the property is an array and it's not empty.
With type hinting we can catch this much earlier in the…
This file contains hidden or 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 | |
| /** | |
| * Custom Error Handler for E_RECOVERABLE_ERROR | |
| * | |
| * http://stackoverflow.com/a/2468534/285564 | |
| * | |
| * @param $errno | |
| * @param $errstr | |
| * @param $errfile | |
| * @param $errline | |
| * @return bool | |
| * @throws ErrorException | |
| */ | |
| function myErrorHandler( $errno, $errstr, $errfile, $errline ) { | |
| if ( E_RECOVERABLE_ERROR===$errno ) { | |
| echo "'catched' catchable fatal error\n"; | |
| throw new ErrorException( $errstr, $errno, 0, $errfile, $errline ); | |
| // return true; | |
| } | |
| return false; | |
| } | |
| // Set up the custom error handler | |
| set_error_handler( 'myErrorHandler' ); | |
| /** | |
| * Class Arr_Test | |
| */ | |
| class Arr_Test { | |
| /** | |
| * Gives us a property to play with | |
| * @var array | |
| */ | |
| var $objArr = array(); | |
| /** | |
| * Our object constructor | |
| * @param array $myArr | |
| */ | |
| public function __construct( $myArr = array() ) { | |
| // Initialize our property to the value of the passed param | |
| $this->objArr = $myArr; | |
| // call a method to test this code | |
| $this->print_myarr(); | |
| } | |
| /** | |
| * Simply iterates an array | |
| */ | |
| protected function print_myarr(){ | |
| if ( is_array( $this->objArr ) ) { | |
| if ( count( $this->objArr ) > 0 ) { | |
| for ( $i=0; $i < count( $this->objArr ); $i++) { | |
| echo $this->objArr[$i]; // this would fail if our property is not an array | |
| } | |
| } else { | |
| echo "objArr is empty"; | |
| } | |
| } else { | |
| echo "not an array"; | |
| } | |
| } | |
| } | |
| try { | |
| $my_string_var = 'I am a string'; | |
| $myObj1 = new Arr_Test( $my_string_var ); | |
| } catch (Exception $e) { | |
| echo $e->getMessage(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment