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?
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.
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()
).
精彩评论