• Welcome to Tux Reports: Where Penguins Fly. We hope you find the topics varied, interesting, and worthy of your time. Please become a member and join in the discussions.

Type Declarations

Tip.png


In passing a parameter to a function or method, type declaration or hinting can be useful to ensure the correct parameter type is passed to the function. For example, a requirement to pass an array involves placing the word array in front of the parameter.

Create a file named typeDeclaration.php and insert the following code.

PHP:
<?php

function testType(array $myArray) {
  var_dump($myArray);
}

$anyArray = array(5,6,7);
$test = testType($anyArray);

echo '<h2>Another Test</h2>';

$noArray = 1;
$buggeredTest = testType($noArray);

Run this in the file in the browser. You should get something similar to these messages.

Type Declaration Array Dump.png


The first var_dump works as expected because an array is being passed. The second test is not using an array and a Catchable fatal error is produced.

The PHP manual provides a listing of type declarations and the PHP versions required to use them.

Type Declaration.png

Blog entry information

Author
LPH
Views
1,348
Last update

More entries in Technology

More entries from LPH

Top