define a closure as method from class

Posted by user272839 on Stack Overflow See other posts from Stack Overflow or by user272839
Published on 2010-05-21T10:35:06Z Indexed on 2010/05/21 11:40 UTC
Read the original article Hit count: 225

Filed under:
|
|

Hi,

i'm trying to play with php5.3 and closure.

I see here (Listing 7. Closure inside an object : http://www.ibm.com/developerworks/opensource/library/os-php-5.3new2/index.html) that it's possible to use $this in the callback function, but it's not. So I try to give $this as use variable :

$self = $this;
$foo = function() use($self) { //do something with $self }

So to use the same example :

class Dog
{
private $_name;
protected $_color;

public function __construct($name, $color)
{
     $this->_name = $name;
     $this->_color = $color;
}
public function greet($greeting)
{
     $self = $this;
     return function() use ($greeting, $self) {
         echo "$greeting, I am a {$self->_color} dog named {$self->_name}.";
     };
}
}

$dog = new Dog("Rover","red");
$dog->greet("Hello");

Output: Hello, I am a red dog named Rover.

First of all this example does not print the string but return the function, but that's not my problem.

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 :

function greet($greeting, $object) {
    echo "$greeting, I am a {$self->_color} dog named {$self->_name}.";
}

And I want :

public function greet($greeting) {
    echo "$greeting, I am a {$self->_color} dog named {$self->_name}.";
}

Which is from Dog and not global.

I hope that I am clear ...

© Stack Overflow or respective owner

Related posts about php

Related posts about closure