Jump to content

Obtaining variables from function's parent


Recommended Posts

Ok, the deal is as follows: I've got a function in a class.Within that function is another function called by uasort(), a custom array sorting function.The main function contains some variables which should be used in the sorting function.However I do not know how they can be accessed, and they can't be included as extra arguments in the function because the uasort only allows 2. Example:

function somefunction()	{	$bar=5;	$foo=4; 	function sorter($arg1,$arg2)		{		$bar & $foo should be accessed from here...		} 	uasort($someArray,"sorter");	}

If there's any way to access $bar & $foo from the sorting function please let me know. Gr.Viller

Link to post
Share on other sites

I think that the only way is to use global variables. Is it not possible to define those variables inside the sort function? You could also make those variables properties of the class and also define the sort function as a class method, and then it will have access to the other properties and methods in the class.

Link to post
Share on other sites

There are examples on the manual page for usort that you should check, but you use an array to specify the object and method name.

class Sort{  public $foo;  public $bar;   public function __construct()  {	$this->foo = 1;	$this->bar = 2;  }   public function compare($a, $  {	echo $this->foo . $this->bar;  }   public function do_sort()  {	uasort($array, array($this, 'compare'));  }} $sorter = new Sort();$sorter->do_sort();

http://www.php.net/manual/en/function.usort.php

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...