tags:

views:

74

answers:

4

PHP scripts register.php:

$compareUser = new User();
   $user = new User;

verify.php (executes with a link from register.php, passes two variables to User.php)

User.php

setActive($token, $uid){
   $this->username = /????
}

*assuming that User has a username property, which instance of the User class will $this take? $compareUser or $user?

+4  A: 

That depends entirely on which object you call setActive() on. You cannot simply write...

setActive('foo', 'bar');

You must write one of these two:

$compareUser->setActive('foo', 'bar');
$user->setActive('foo', 'bar');

In either case, $this is whichever object you used to invoke that method. That is, in fact, the exact purpose of the $this variable.

VoteyDisciple
+2  A: 
class User {
  var $username;
  function User($name) {
    $this->username = $name;
  }
  function setActive($token, $uid) {
    echo $this->username;
  }
}

$user1 = new User('tom');
$user2 = new User('sally');

$user1->setActive(1, 2); // tom
$user2->setActive(1, 2); // sally

Make sure setActive is defined in the class definition like in the above. Hopefully the above helps clear things up.

camomileCase
A: 

$this is context-sensitive - it always refers to the current context in which code is running.

It is not possible to refer to $this unless you call it from within a (non-static) class method. When you do, $this refers to whichever instance of the class invoked that method upon run-time.

thomasrutter
A: 

The "without specifying which" part of our initial question is where you're wrong.

As the examples have shown: It is not possible to use an "unspecified" $this, since it is always called from within one certain instance of that class.

Edited to illustrate my comment:

class Foo
{
  protected $var;

  function _construct( $var )
  {
    $this->var = $var;
  }

  function echoVar()
  {
    // Works since it's within a class and points to an instance's variable:
    echo $this->var; 
  }
}

$first = new Foo( 'first' );
$second = new Foo( 'second' );

// These will work:
$first->echoVar();
$second->echoVar();

// This won't. What's it supposed to show?
$this->echoVar();
Jörg
hm...my bad...maybe what I'm trying to say is when there are two instances of a class at runtime, what will $this point to? I guess it is the latest declared right?
No. Still, this is where you're wrong: You will always be (and cannot do anything else) using $this from with in ONE specific instance! You can never refer to one (or a number of instances) from outside using $this. So $this never has to "choose" an instance.
Jörg