Move from one function to another

2

I have two functions in a class, how do I get the value of a variable that is inside a function and take advantage of that same variable in another function of the same class. I want to make the variable $ userFullname Global to be used in every class.

public function GetHtml($data)
{

    $this->data = $data;
    $quizinfo   = $this->data['quizinfo'];
    $quizinfo   = (object) $quizinfo;           

    foreach ($this->data['users'] as $key => $user) {

        $userFullname = $user['firstname'] . $user['lastname'];  
    }
    
asked by anonymous 20.05.2016 / 15:34

2 answers

3

Make this local variable in a member of the class to do this just set it shortly after the class name.

class usuario{
   private $userFullname; //<--- definição do membro da classe

   public function GetHtml($data){
      $this->data = $data;
      $quizinfo   = $this->data['quizinfo'];
      $quizinfo   = (object) $quizinfo;     

      foreach ($this->data['users'] as $key => $user) {
         //aqui a atribuição mudou
         $this->userFullname = $user['firstname'] . $user['lastname'];
      }

Detail this is just the codend ceiling provided in the question, so userFullname will always have the last user in the list, if you want to store the whole list use brackets in the $this->userFullname[] = 'algo';

    
20.05.2016 / 15:49
2
class usuario() {
     public $userFullname;

     public function __construct($data) {
         $this->userFullname = $this->GetHtml($data);
     }

     protected function GetHtml($data) {
         $this->data = $data;
         $quizinfo   = $this->data['quizinfo'];
         $quizinfo   = (object) $quizinfo;     

         foreach ($this->data['users'] as $key => $user) {
            $userFullname = $user['firstname'] . $user['lastname'];
         }
         return $userFullname;
     }

}

$user = new usuario($data);
echo $user->userFullname;

This will be available whenever an instance of object usuario is created, it is no longer necessary to execute GetHtml();

    
20.05.2016 / 15:39