<?xml version="1.0" encoding="iso-8859-1"?>
<!-- $Revision: 1.3 $ -->
 <sect1 id="language.oop5.typehinting">
  <title>Type Hinting</title>
  <para>
   PHP 5 introduces Type Hinting. Functions are now able to force parameters
   to be objects (by specifying the name of the class in the function
   prototype) or arrays (since PHP 5.1).
  </para>
  
  <example>
   <title>Type Hinting examples</title>
    <programlisting role="php">
<![CDATA[
<?php
// An example class
class MyClass
{
    /**
     * A test function
     *
     * First parameter must be an object of type OtherClass
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }


    /**
     * Another test function
     *
     * First parameter must be an array
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }
}

// Another example class
class OtherClass {
    public $var = 'Hello World';
}
?>
]]>
   </programlisting>
   <para>
    Failing to satisfy the type hint results in a fatal error.
   </para>
    <programlisting role="php">
<![CDATA[
<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);

// Fatal Error: Argument 1 must not be null
$myclass->test(null);

// Works: Prints Hello World
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');

// Works: Prints the array
$myclass->test_array(array('a', 'b', 'c'));
?>
]]>
   </programlisting>
   <para>
    Type hinting also works with functions:
   </para>
    <programlisting role="php">
<![CDATA[
<?php
// An example class
class MyClass {
    public $var = 'Hello World';
}

/**
 * A test function
 *
 * First parameter must be an object of type MyClass
 */
function MyFunction (MyClass $foo) {
    echo $foo->var;
}

// Works
$myclass = new MyClass;
MyFunction($myclass);
?>
]]>
   </programlisting>
  </example>
  <para>
   Type Hints can only be of the <type>object</type> and <type>array</type>
   (since PHP 5.1) type. Traditional type hinting with <type>int</type> and
   <type>string</type> isn't supported.
  </para>
 </sect1>
 
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"../../manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->