[prev in list] [next in list] [prev in thread] [next in thread] 

List:       php-doc-cvs
Subject:    [DOC-CVS] =?utf-8?q?svn:_/phpdoc/en/trunk/language/_functions.xml?=
From:       Peter_Cowburn <salathe () php ! net>
Date:       2014-11-18 11:02:31
Message-ID: svn-salathe-1416308551-335191-736658212 () svn ! php ! net
[Download RAW message or body]

salathe                                  Tue, 18 Nov 2014 11:02:31 +0000

Revision: http://svn.php.net/viewvc?view=revision&revision=335191

Log:
Basic closure examples (doc bug #61857)

Bug: https://bugs.php.net/61857 (Re-Opened) Extra clarification around closures required
      
Changed paths:
    U   phpdoc/en/trunk/language/functions.xml

Modified: phpdoc/en/trunk/language/functions.xml
===================================================================
--- phpdoc/en/trunk/language/functions.xml	2014-11-17 22:28:57 UTC (rev 335190)
+++ phpdoc/en/trunk/language/functions.xml	2014-11-18 11:02:31 UTC (rev 335191)
@@ -831,6 +831,69 @@
    <simpara>
     Closures may also inherit variables from the parent scope.
     Any such variables must be passed to the <literal>use</literal> language construct.
+   </simpara>
+
+   <example>
+    <title>Inheriting variables from the parent scope</title>
+    <programlisting role="php">
+<![CDATA[
+<?php
+$message = 'hello';
+
+// No "use"
+$example = function () {
+    var_dump($message);
+};
+echo $example();
+
+// Inherit $message
+$example = function () use ($message) {
+    var_dump($message);
+};
+echo $example();
+
+// Inherited variable's value is from when the function
+// is defined, not when called
+$message = 'world';
+echo $example();
+
+// Reset message
+$message = 'hello';
+
+// Inherit by-reference
+$example = function () use (&$message) {
+    var_dump($message);
+};
+echo $example();
+
+// The changed value in the parent scope
+// is reflected inside the function call
+$message = 'world';
+echo $example();
+
+// Closures can also accept regular arguments
+$example = function ($arg) use ($message) {
+    var_dump($arg . ' ' . $message);
+};
+$example("hello");
+?>
+]]>
+    </programlisting>
+    &example.outputs.similar;
+    <screen>
+<![CDATA[
+Notice: Undefined variable: message in /example.php on line 6
+NULL
+string(5) "hello"
+string(5) "hello"
+string(5) "hello"
+string(5) "world"
+string(11) "hello world"
+]]>
+    </screen>
+   </example>
+
+   <simpara>
     Inheriting variables from the parent scope is <emphasis>not</emphasis>
     the same as using global variables.
     Global variables exist in the global scope, which is the same no



-- 
PHP Documentation Commits Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic