Nicolas de Fontenay
Nicolas de Fontenay

Reputation: 2200

Oriented Object question on object's context

If I have a class like this:

class1{
  public function doSomething($value, class2 $object){
    $object->setAVariable($value);
  }
}

class2{
  protected $AVariable;

  public setAVariable($value){
    $this->AVariable = $value;
    return $this->AVariable;
  }

  public getAVariable(){
    return $this->AVariable;
  }
}

in test.php:

$object2 = new class2();
$object1 = new class1();
$value = 12;
$object1->doSomething(12, $object2);

Question:

Still in test.php, can I access $value like this:

echo $object2->getAVariable();

which would return 12?

Upvotes: 0

Views: 72

Answers (2)

usoban
usoban

Reputation: 5478

Fix doSomething method in class1 to:

  public function doSomething($value, class2 $object){
    $object->setAVariable($value);
  }

And it will be ok. Your example, however, doesn't work, but I assume it is typing mistake.

Upvotes: 1

KingCrunch
KingCrunch

Reputation: 132051

No, because $object1 in class1:doSomething() is undefined. If you use $object there instead, it will work, because doSomething() will call $object->setAVariable(), what is in this case the same object, like $object2 fromt the outer scope (you gave that object to doSomethig()).

Upvotes: 0

Related Questions