How to reuse data in a class without having to repeat this data?

Asked

Viewed 111 times

0

How to reuse $dados, $key and $postFields in all methods without having to repeat this data every time within each method? Yes, these variables will always have the same values.

class AllImoveis
{
    /**
     * Chaves de Autenticação
     * @var string
    */
    public function listar_imoveis()
    {
    $dados = array(fields =>array('tipo', 'cidade', 'bairro', 'codigo'));
    $key = '82CDA6l0BBepOykevP0472xl9ZoKuIlH';
    $postFields = json_encode($dados);  
    ...

    ...
    }
    public function listar_imovel()
    {
    $dados = array(fields =>array('tipo', 'cidade', 'bairro', 'codigo'));
    $key = '82CDA6l0BBepOykevP0472xl9ZoKuIlH';
    $postFields = json_encode($dados);  
    ...

    ...
    }
}
  • 1

    It depends on what you want. Without a context it’s hard to say. Maybe you should repeat it. Maybe I should create a method that returns them or makes more granular manipulations, maybe I should turn them into class fields, maybe I should create an auxiliary class, maybe I should not do any of this and look for a solution that you dominate.

2 answers

2


To $dados and $key cire constants since the value will not change, $postFields will become a class attribute.

class AllImoveis {
  const KEY = '82CDA6l0BBepOykevP0472xl9ZoKuIlH';
  const DADOS = array(fields =>array('tipo', 'cidade', 'bairro', 'codigo'));
  private $postFields;
  • One more small question ... how do I insert the const in the method?

  • @Marcosvinicius you can’t do that.

1

so that the values are constant declare as, const NOME_DA_CONSTANTE without the dollar sign. to use inside the methods call the variable this way::NOME_DA_CONSTANTE is not mandatory but is recommended to use uppercase for constants.

Browser other questions tagged

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