Note that there are some explanatory texts on larger screens.

plurals
  1. POdefine a closure as method from class
    primarykey
    data
    text
    <p>i'm trying to play with php5.3 and closure.</p> <p>I see here (Listing 7. Closure inside an object : <a href="http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html" rel="noreferrer">http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html</a>) that it's possible to use $this in the callback function, but it's not. So I try to give $this as use variable :</p> <pre><code>$self = $this; $foo = function() use($self) { //do something with $self } </code></pre> <p>So to use the same example :</p> <pre><code>class Dog { private $_name; protected $_color; public function __construct($name, $color) { $this-&gt;_name = $name; $this-&gt;_color = $color; } public function greet($greeting) { $self = $this; return function() use ($greeting, $self) { echo "$greeting, I am a {$self-&gt;_color} dog named {$self-&gt;_name}."; }; } } $dog = new Dog("Rover","red"); $dog-&gt;greet("Hello"); Output: Hello, I am a red dog named Rover. </code></pre> <p>First of all this example does not print the string but return the function, but that's not my problem.</p> <p>Secondly I can't access to private or protected, because the callback function is a global function and not in the context from the Dog object. Tha't my problem. It's the same as :</p> <pre><code>function greet($greeting, $object) { echo "$greeting, I am a {$self-&gt;_color} dog named {$self-&gt;_name}."; } </code></pre> <p>And I want :</p> <pre><code>public function greet($greeting) { echo "$greeting, I am a {$self-&gt;_color} dog named {$self-&gt;_name}."; } </code></pre> <p>Which is from Dog and not global.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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