473,698 Members | 2,398 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

Hi,

I'm trying to use preg_replace_ca llback within a method. The
preg_replace_ca llback() & 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($mat ches){
return $this->properties[$matches[1]]
}
function mymethod ($subject){
$mystr = preg_replace_ca llback(
"!{([a-z]+)}!",
array($this,'my callback'),
$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 4472
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**********@g mail.com> wrote in message
news:11******** *************@g 43g2000cwa.goog legroups.com...
Hi,

I'm trying to use preg_replace_ca llback within a method. The
preg_replace_ca llback() & 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($mat ches){
return $this->properties[$matches[1]]
}
function mymethod ($subject){
$mystr = preg_replace_ca llback(
"!{([a-z]+)}!",
array($this,'my callback'),
$subject
)
}
...
}
Have you tried using the create_function property? If you read the
documentation page for preg_replace_ca llback (*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,$v al){ $this->vars[$name] = $val; }
function output(){
$fileContents = file_get_conten ts("my.template ");
$outputString = preg_replace_ca llback(
'@{([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.co m");
$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,$v al){ $this->vars[$name] = $val; }
function output(){
$fileContents = file_get_conten ts("my.template ");
$outputString = preg_replace_ca llback(
'@{([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**********@gm ail.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_ca llback( ... 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.u k :: 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.u k :: 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
2635
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
1937
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); with the METH_O calling convention? The type is already created, I cannot insert it into the tp_methods array anymore.
90
3970
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 and binding since Greg originally posted his meowing cat message that it's hard to remember what the original problem was that Greg pointed out. At that time Prothon had no solution for the problem. Now there is a released solution but it is...
0
1722
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. Using the code below, I receive the error message: "AttributeError: 'PySwigObject' object has no attribute 'GetName'" The python callback function is being passed in through the clientdata
4
2050
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
1845
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 others you can find by Googling, but I wanted to try doing it myself and needed some advice on different approaches. Most signal/slot libraries are based on template classes containing a pointer-to-object and pointer-to-memfunc. You can also do...
5
1770
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 firing the callback delgate from within one of the new threads. So far, all is well but I'm curious as to what, threading wise, is going on there. I'm instantiating the class in the app thread (say 1) and providing a method to call when...
2
1497
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 function/method is defined on. Finding the name of the class where the method we just entered was defined in is a bit tricky. Here's a snippet of the test code: class Base: @tracelevel(1)
7
1517
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 port)
0
8609
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9166
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9030
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5861
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4621
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2333
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.