By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,714 Members | 1,305 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,714 IT Pros & Developers. It's quick & easy.

accessing $this within callback?

P: n/a
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
Jul 17 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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

Jul 17 '05 #2

P: n/a
> 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
Jul 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.