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 ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
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 |
|
|||
|
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 |
|
|||
|
> 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 |