php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #47690 $this not accessible inside a lambda function declared within a class
Submitted: 2009-03-17 14:01 UTC Modified: 2009-03-17 14:59 UTC
From: crocodile2u at gmail dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.3CVS-2009-03-17 (snap) OS: ubuntu 8.10
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: crocodile2u at gmail dot com
New email:
PHP Version: OS:

 

 [2009-03-17 14:01 UTC] crocodile2u at gmail dot com
Description:
------------
http://wiki.php.net/rfc/closures in the "Interaction with OOP" section, it is said that $this is accessible from within a lambda-function that is declared in a method. This is not true for php-5.3.0beta.

Reproduce code:
---------------
<?php
// code completely taken from http://wiki.php.net/rfc/closures
class Example {
       private $search;
 
       public function __construct ($search) {
         $this->search = $search;
       }
 
       public function setSearch ($search) {
         $this->search = $search;
       }
 
       public function getReplacer ($replacement) {
         return function ($text) use ($replacement) {
           return str_replace ($this->search, $replacement, $text);
         };
       }
     }
 
     $example = new Example ('hello');
     $replacer = $example->getReplacer ('goodbye');
     echo $replacer ('hello world'); // goodbye world
     $example->setSearch ('world');
     echo $replacer ('hello world'); // hello goodbye

Expected result:
----------------
no errors occur

Actual result:
--------------
Fatal error: Using $this when not in object context in /home/vbolshov/tmp/x.php on line 16

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2009-03-17 14:24 UTC] crocodile2u at gmail dot com
Ok, Thanks for a quick reply.

I would suggest adding that link to the wiki article. (I have just registered in the wiki but there is no "Edit this page" button there for me, guess it is a priviledge that I do not have).
 [2009-03-17 14:59 UTC] scottmac@php.net
I already did it when I saw this report.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Sep 17 05:00:02 2025 UTC