Reputation:
I have 2 classes: User
and Answer
I define in the class User that the name is "Peter"
how can I get the name defined in the User
instance inside the Answer
instance?
$user= new User();
$user->name = "Peter";
$answer = new Answer();
echo $answer->getListAnswer(); //how can I get the name of the User (Peter) in the function getListAnswer() in the Class Answer?
Upvotes: 0
Views: 101
Reputation: 47370
Inject the User
instance into the Answer
instance. Like this, for example:
class Answer
private $user;
public function __construct(User $user) {
$this->user = $user;
}
public function getListAnswer() {
$userName = $this->user->name;
// rest of your method.
// Use $userName where you need it.
}
}
First you create your User
object as usual:
$user = new User();
$user->name = "Peter";
In the constructor for Answer
we declared that it needs (depends on) a User
object. So you pass the user object you just created to instantiate a new Answer
:
$answer = new Answer($user);
echo $answer->getListAnswer();
Upvotes: 4
Reputation: 1
Well I'm not much sure of it, but if you try and define your variable scope with "global " in the Answer class,it might make some difference
Upvotes: -3