473,399 Members | 3,832 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Defining a callback Func for preg_replace_callback(), within some class's method

Hi,

I'm trying to use preg_replace_callback within a method. The
preg_replace_callback() & mycallback() pair will only be used by this
method, and this method will probably only be called once in the
object's lifetime (so there's no sense in making the callback function
a method of the class...(is there??))

Instead, I wanted to use create_function() to create a make-shift
callback function within the method. (seeing as you can't define a
function within a method). However, it needs to be able to access a
property (or its getter) of the object, and it complains that it's not
within the right scope to access it.

What's the best way of doing this?

class myclass {
....
function mycallback($matches){
return $this->properties[$matches[1]]
}
function mymethod ($subject){
$mystr = preg_replace_callback(
"!{([a-z]+)}!",
array($this,'mycallback'),
$subject
)
}
....
}

This above is the only way I've found of making this work so far.
However, mycallback() I really don't think should have the scope it
does, i would like its definition to stay constrained to mymethod().
any ideas would be greatly appreaciated!

Jody

Jan 16 '06 #1
8 4457
What you're trying to do is create a closure, which can't be done in
PHP as far as I know.

Jan 17 '06 #2
d
<jo**********@gmail.com> wrote in message
news:11*********************@g43g2000cwa.googlegro ups.com...
Hi,

I'm trying to use preg_replace_callback within a method. The
preg_replace_callback() & mycallback() pair will only be used by this
method, and this method will probably only be called once in the
object's lifetime (so there's no sense in making the callback function
a method of the class...(is there??))

Instead, I wanted to use create_function() to create a make-shift
callback function within the method. (seeing as you can't define a
function within a method). However, it needs to be able to access a
property (or its getter) of the object, and it complains that it's not
within the right scope to access it.

What's the best way of doing this?

class myclass {
...
function mycallback($matches){
return $this->properties[$matches[1]]
}
function mymethod ($subject){
$mystr = preg_replace_callback(
"!{([a-z]+)}!",
array($this,'mycallback'),
$subject
)
}
...
}
Have you tried using the create_function property? If you read the
documentation page for preg_replace_callback (*ahem*), you'll see an example
:)

http://uk.php.net/manual/en/function...e-callback.php
This above is the only way I've found of making this work so far.
However, mycallback() I really don't think should have the scope it
does, i would like its definition to stay constrained to mymethod().
any ideas would be greatly appreaciated!

Jody

Jan 17 '06 #3
index.php:
<?php
class myclass {
protected $vars = array();
function addVar($name,$val){ $this->vars[$name] = $val; }
function output(){
$fileContents = file_get_contents("my.template");
$outputString = preg_replace_callback(
'@{([A-Z]+)}@',
create_function('$matcharray','return
$this->vars[$matches[1]];'),
$fileContents);
echo $outputString;
} }
$obj = new myclass();
$obj->addVar("NAME", "bob");
$obj->addVar("MOBILE", "0207 PHP RULES");
$obj->addVar("EMAIL", "bo*@bob.com");
$obj->output();
?>

my.template :
<ul>
<li>{NAME}</li>
<li>{MOBILE}</li>
<li>{EMAIL}</li>
</ul>

It produces the error:

Fatal error: Using $this when not in object context in
/www/thisproblem/index.php(10) : runtime-created function on line 1

In the example at
http://uk.php.net/manual/en/function...e-callback.php

They're not implementing a callback function with create_function() in
a class context, as opposed to my example above.

I'm still quite at a loss myself. I'm hazy on my lambda calculus but
surely there's a way round this?

--
J Florian

Jan 17 '06 #4
example.php:
<?php
class myclass {
protected $vars = array();
function addVar($name,$val){ $this->vars[$name] = $val; }
function output(){
$fileContents = file_get_contents("my.template");
$outputString = preg_replace_callback(
'@{([A-Z]+)}@',
create_function('$matcharray','return
$this->vars[$matches[1]];'),
$fileContents);
echo $outputString;
} }

$obj = new myclass();
$obj->addVar("NAME", "bob");
$obj->addVar("MOBILE", "0207 PHP RULES");
$obj->addVar("EMAIL", "b...@bob.com");
$obj->output();
?>

my.template :
<ul>
<li>{NAME}</li>
<li>{MOBILE}</li>
<li>{EMAIL}</li>
</ul>

It produces the error:

Fatal error: Using $this when not in object context in
/www/thisproblem/example.php(10) : runtime-created function on line 1

In the example at
http://uk.php.net/manual/en/function...e-callback.php

They're not implementing a callback function with create_function() in
a class context, as opposed to my example above.

Since it's a) not wise and b) not possible to declare a function within
a method (since it would be re-declared each time the method's used)
I'm still quite at a loss myself

I'm hazy on my lambda calculus but surely there's a way round this,
other than creating a method solely as a one-off callback?

Cheers

--
J Florian

Jan 17 '06 #5
jo**********@gmail.com wrote:

They're not implementing a callback function with create_function() in
a class context, as opposed to my example above.

Since it's a) not wise and b) not possible to declare a function within
a method (since it would be re-declared each time the method's used)
I'm still quite at a loss myself

I'm hazy on my lambda calculus but surely there's a way round this,
other than creating a method solely as a one-off callback?


Given it a rest. Like I said, PHP does not have built-in support for
closure. It's possible to implement a closure class, of course. But
then you end up with an additional class floating around instead of a
method.

If you hate having an extra method that much, just have the method call
itself and branch based on the parameter passed. Example:

function output($param = null){
if($param) {
}
else {
$outputString = preg_replace_callback( ... array($this,
'output') ... );
}
}

Jan 17 '06 #6
On 16 Jan 2006 17:40:31 -0800, "Chung Leong" <ch***********@hotmail.com> wrote:
What you're trying to do is create a closure, which can't be done in
PHP as far as I know.


create_function() gets close to this.

--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool
Jan 17 '06 #7

Andy Hassall wrote:
On 16 Jan 2006 17:40:31 -0800, "Chung Leong" <ch***********@hotmail.com> wrote:
What you're trying to do is create a closure, which can't be done in
PHP as far as I know.


create_function() gets close to this.

--
Andy Hassall :: an**@andyh.co.uk :: http://www.andyh.co.uk
http://www.andyhsoftware.co.uk/space :: disk and FTP usage analysis tool


There is no good way to bind a reference to the function though, aside
from (a) a variable global (b) a wrapper class plus the array($obj,
'function') construct. PHP evidently doesn't allow lambda functions to
have static variable, so you can't give a function a private variable.

Jan 18 '06 #8
>> Given it a rest

lol. I will. I've been convinced.

Thanks for everyone's help

Jan 18 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Ian.H | last post by:
Hi all, I'm trying to write a PHP colour parser and after various attempts, something, somewhere trips it over. Some details: String to parse: $origString = '^1foo^5bar';
12
by: Thomas Heller | last post by:
I once knew how to do it, but I cannot find or remember it anymore: How can I attach *class* methods to a type in C code, when I have a function PyObject *func(PyObject *type, PyObject *arg);...
90
by: Mark Hahn | last post by:
"Michael Geary" <Mike@Geary.com> wrote ... >Does anyone have some sample code where obj$func() would be used? > (Apologies if I missed it.) There have been so many messages about delegation...
0
by: Jeff | last post by:
I'm trying to pass a proxy class instance (SWIG generated) of CClass, to a python callback function from C++. The proxy class instance of CClass is created from a pointer to the C++ class CClass....
4
by: ma740988 | last post by:
// file sltest.h #ifndef SLTEST_H #define SLTEST_H class CallbackBase // herb shutters gotW source .. { public: virtual void operator()() const { }; virtual ~CallbackBase() = 0; };
2
by: Damien | last post by:
Hi all, I'm messing around with various signal/slot mechanisms, trying to build something lean and fast. I've used libsigc++, and Sarah Thompson's at sigslot.sourceforge.net, and most of the...
5
by: greg.merideth | last post by:
I have a class that I've provided an event for to be called when the processing in the class is complete (a callback). The class spins up a series of threads for the background operation and I'm...
2
by: lcaamano | last post by:
We have a tracing decorator that automatically logs enter/exits to/from functions and methods and it also figures out by itself the function call arguments values and the class or module the...
7
by: Rester | last post by:
//the simple code template<typename T> class CallBack { public: typedef void (T::*Func)(unsigned short); CallBack(T *t, Func f):_t(t),_f(f) {} void operator()(unsigned short...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.