如何从另一个班级的一个班级获取变量?

时间:2019-07-12 08:54:06

标签: php class oop

我有2个班级:UserAnswer

我在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?

2 个答案:

答案 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”定义变量范围,则可能会有所不同