aidan Sun Oct 3 01:07:04 2004 EDT
Modified files:
/phpdoc/en/language/oop5 typehinting.xml
Log:
Added more information and made the examples easier to understand
http://cvs.php.net/diff.php/phpdoc/en/language/oop5/typehinting.xml?r1=1.1&r2=1.2&ty=u
Index: phpdoc/en/language/oop5/typehinting.xml
diff -u phpdoc/en/language/oop5/typehinting.xml:1.1
phpdoc/en/language/oop5/typehinting.xml:1.2
--- phpdoc/en/language/oop5/typehinting.xml:1.1 Sun Oct 3 00:36:35 2004
+++ phpdoc/en/language/oop5/typehinting.xml Sun Oct 3 01:07:04 2004
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="iso-8859-1"?>
-<!-- $Revision: 1.1 $ -->
+<!-- $Revision: 1.2 $ -->
<sect1 id="language.oop5.typehinting">
<title>Type Hinting</title>
<para>
- PHP 5 introduces Type Hinting. Methods are now able to force parameters
+ 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.
</para>
@@ -12,6 +12,7 @@
<programlisting role="php">
<![CDATA[
<?php
+// An example class
class MyClass
{
/**
@@ -24,29 +25,70 @@
}
}
+// 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;
-// These are fatal errors
-// Argument 1 must be an object of class OtherClass
+// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');
-// Argument 1 must be an instance of OtherClass
+
+// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);
-// Argument 1 must not be null
+
+// Fatal Error: Argument 1 must not be null
$myclass->test(null);
-// This is fine
-$foo = new OtherClass;
-// Prints Hello World
-$myclass->test($foo);
-?>
+// Works: Prints Hello World
+$myclass->test($otherclass);
+?>
+]]>
+ </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> type. Traditional
+ type hinting with <type>int</type> and <type>string</type> are not
+ supported.
+ </para>
</sect1>
<!-- Keep this comment at the end of the file