define a closure as method from class

后端 未结 4 401
Happy的楠姐
Happy的楠姐 2020-12-18 21:34

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/in

4条回答
  •  [愿得一人]
    2020-12-18 21:55

    As of PHP 5.4.0 Alpha1, you can access $this from within the context of an object instance:

    _name = $name;
        $this->_color = $color;
      }
    
      public function greet($greeting)
      {
        $func = function() use ($greeting) {
          echo "$greeting, I am a {$this->_color} dog named {$this->_name}.";
        };
    
        $func();
      }
    }
    
    $dog = new Dog("Rover","red");
    $dog->greet("Hello");
    

    You can also do this:

    $dog = new Dog("Rover", "red");
    $getname = Closure::bind($dog, function() { return $this->_name; });
    echo $getname(); // Rover
    

    As you can see, it's possible to easily mess with private data... so be careful.

提交回复
热议问题