我有2个班级:User
和Answer
我在User类中定义名称为“ Peter”
如何获取User
实例中Answer
实例中定义的名称?
$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?
答案 0 :(得分:3)
将User
实例注入到Answer
实例中。像这样:
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.
}
}
首先,您像往常一样创建User
对象:
$user = new User();
$user->name = "Peter";
在Answer
的构造函数中,我们声明它需要一个User
对象。因此,您传递了刚创建的用户对象以实例化新的Answer
:
$answer = new Answer($user);
echo $answer->getListAnswer();
答案 1 :(得分:-2)
我不太确定,但是如果您尝试在Answer类中使用“ global”定义变量范围,则可能会有所不同