faqts : Computers : Programming : Languages : PHP : kms : Classes

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

$this and $that

Dec 7th, 2005 16:52
Tim Wood,


Someone posted the question
"How to get the class instance name, so that "$this->a_method could be
passed as a variable function?"
(http://www.faqts.com/knowledge_base/view.phtml/aid/7705/fid/39)

I'm sure FAQTS experts know how to answer questions, but there is no
link no answer no nothing about how to do this.  Hopefully, the question
asker will find this.

The basic answer is that you pass "$this" (a reference to the current
class instance) to the a function in the other class.  The function you
call in the other class has to accept it as a reference (that's the &
before the variable name in function callback.

I've rolled two examples below.

The first (called below as $zz->tell_y_to_callback() ) just demonstrates
passing this so the other object can send a call back.

The second (called below as $zz->tell_y_to_supercallback() ) passes both
$this and the name of a function so $zz can send some data back to a
specified function.  So, you could supercallback2 and so on to z and
change the behavior of y by just changing the function name you pass to y...

class y {
  function callback( &$obj ) {
    $obj->listener();
  }

  function supercallback( &$obj, $fn ) {
    $obj->$fn('shout back');
  }
}

class z {
  function tell_y_to_callback() {
    $GLOBALS['yy']->callback( $this );
  }
  function tell_y_to_supercallback() {
    $GLOBALS['yy']->callback( $this, 'superlistener' );
  }
  function listener() {
    print 'made it back';
  }
  function superlistener( $string ) {
    print $string;
  }
}

$zz = new z;
$yy = new y;
$zz->tell_y_to_callback();
$zz->tell_y_to_supercallback();