accessing $this within callback?

This is a discussion on accessing $this within callback? within the PHP Language forums, part of the PHP Programming Forums category; I'm using usort() to sort a complex array of arrays. The usort call is wrapped in a sort method ...


Go Back   Usenet Forums > PHP Programming Forums > PHP Language

FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 10-08-2004
Coder Droid
 
Posts: n/a
Default accessing $this within callback?

I'm using usort() to sort a complex array of arrays. The usort call is
wrapped in a sort method of my own class. The cmp() callback is also a
method of the class. Something like this:

class foo {

function foo() {
$this->thing = array();
$this->bar = 123;
}

function cmp($a, $b) {
print $this->bar; // $this undefined?
}

function sort() {
usort($this->thing, array("foo", "cmp"));
}

}

However, $this seems to be undefined in the cmp() block. Is that just
the way it is? Or is there something I need to do to either expose it,
or call it in a different manner?

TIA,

--cd


Reply With Quote
  #2 (permalink)  
Old 10-09-2004
Janwillem Borleffs
 
Posts: n/a
Default Re: accessing $this within callback?

Coder Droid wrote:
> However, $this seems to be undefined in the cmp() block. Is that just
> the way it is? Or is there something I need to do to either expose it,
> or call it in a different manner?
>


Change the sort() method into the following:

function sort() {
usort($this->thing, array($this, "cmp"));
}

Also, don't forget to put something in the $thing array; on empty arrays,
the cmp() method will not be called.


JW



Reply With Quote
  #3 (permalink)  
Old 10-09-2004
Coder Droid
 
Posts: n/a
Default Re: accessing $this within callback?

> Change the sort() method into the following:
>
> function sort() {
> usort($this->thing, array($this, "cmp"));
> }


Ta da! That was it... thank you. I don't know why I didn't think of
that. Sheesh!

> Also, don't forget to put something in the $thing array; on empty

arrays,
> the cmp() method will not be called.


Of course ... my example was just for illustrative purposes: an array
placeholder to avoid having to type out my complex array just for the
example. I figured $this not existing didn't have anything to with my
array value. (Not that that couldn't have been a bad assumption.)

Again, thanks for pointing out the obvious to me!

--cd


Reply With Quote
Reply
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are Off
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On




All times are GMT +1. The time now is 08:00 AM.


Powered by vBulletin® Version 3.7.3
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO 3.0.0