Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Proper anonymous functions / closures are only available in PHP 5.3, which will not be widely available for a while - <a href="http://wiki.php.net/rfc/closures" rel="nofollow noreferrer">some useful information</a>. I don't think it is really possible to do what you want.</p> <p>You can use <code>create_function()</code> to an extent:</p> <pre><code>$func = create_function('$baz', ' echo strtoupper($baz); '); $func("hello"); </code></pre> <p>However the following does not work as you would expect:</p> <pre><code>$foo = new Foo; $foo-&gt;bar = create_function('$baz', ' echo strtoupper($baz); '); $foo-&gt;bar('lorem ipsum dolor sit amet'); </code></pre> <p>You would need to do instead:</p> <pre><code>call_user_func($foo-&gt;bar, 'lorem ipsum dolor sit amet'); </code></pre> <p>Also you can't use <code>$this</code> inside the created function because its scope would not be the same as a method.</p> <p><strong>Edit</strong></p> <p>I accidentally duplicated some of Martijn's answer as he edited his while I was writing mine. I will leave my answer intact for the sake of completeness</p> <p><strong>Another edit</strong></p> <p>You could maybe also do something like</p> <pre><code>class Foo { public $bar; protected $anonFuncs = array(); public function create_method($name, $params, $code) { if (strlen($params)) $params .= ','; $params .= '$self'; $this-&gt;anonFuncs[$name] = create_function($params, $code); } public function __call($name, $args) { if (!isset($this-&gt;anonFuncs[$name])) { trigger_error("No method $name", E_USER_ERROR); } $args[] = $this; return call_user_func_array($this-&gt;anonFuncs[$name], $args); } } $foo = new Foo; $foo-&gt;create_method('bar', '$baz', ' echo strtoupper($baz) . get_class($self); '); $foo-&gt;bar('lorem ipsum dolor sit amet'); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload