note 30886 modified in function.create-function by danbrown

From: Date: Sat, 19 Jul 2008 21:29:15 +0000
Subject: note 30886 modified in function.create-function by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-141757@lists.php.net to get a copy of this message
[EDIT by danbrown AT php DOT net: Combined user-corrected post with previous (incorrect) post.] You can't refer to a class variable from an anonymous function inside a class method using $this. Anonymous functions don't inherit the method scope. You'll have to do this: <?php class AnyClass { var $classVar = 'some regular expression pattern'; function classMethod() { $_anonymFunc = create_function( '$arg1, $arg2', 'if ( eregi($arg2, $arg1) ) { return true; } else { return false; } ' ); $willWork = $_anonymFunc('some string', $classVar); } } ?> --was-- What I posted above is logical because anonymous functions don't inherit the method scope. You'll have to do this: <?php class AnyClass { var $classVar = 'some regular expression pattern'; function classMethod() { $_anonymFunc = create_function( '$arg1, $arg2', 'if ( eregi($arg2, $arg1) ) { return true; } else { return false; } ' ); $willWork = $_anonymFunc('some string', $classVar); } } ?> http://php.net/manual/en/function.create-function.php

« previous php.notes (#141757) next »