Moving from one function to another

Asked

Viewed 63 times

2

I have two functions in one class, how to do to take the value of a variable that is within 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'];  
    }
  • 1

    Make this variable (local) a class member

  • 2

    You have two functions in class or has two methods. Need to be clearer. If possible, enter the code for us to analyze

  • 1

    Humberto, just to understand the difference: funções are reusable code snippets, are declared class independent. métodos are the "functions" you define in a class. Just to understand the names

2 answers

3

Make this variable local, in a class member to do this just set it right 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 Code Techo provided in the question, so userFullname will always have the last user of the list, if you want to store the full list use brackets in the assignment $this->userFullname[] = 'algo';

  • So he will always have to execute the method GetHtml before accessing the property $userFullname

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 object instance is created usuario, need not execute before the GetHtml();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.