PHP concatenate string + variable with obj->method

Asked

Viewed 1,011 times

0

I want to call a method automatically if certain situation occurs for this I am trying to put together the name of this method.

The methods for which I will do this are gets and seters:

$obj->get  +   $restanteDoNomeDoMetodo + ()

when trying to perform this merge, this error occurs, the code interpreter is identifying get as variable, and it is part of the name of a method that exists in a class some idea of how to solve it?

I tried some variations to concatenate as terms between '' and {} they all result in error

$stmt->bindValue(":{$this->columns[$i]}",
                 $this->entity->{'get'.ucfirst($this->columns[$i]).'()'});

Could someone help me in this matter already thank you.

Erro: Notice: Undefined property: Cliente::$getNome() in
      C:\Users\Vinicius\Desktop\pdo\ServiceDb.php on line 67
1 
  • First read: http://php.net/manual/en/language.oop5.magic.php and http://php.net/manual/en/language.oop5.overloading.php#Object.get and http://php.net/manual/en/language.oop5.overloading.php#Object.set the way you are doing this wrong... !!! read the 3 links!

  • You have a possible solution: https://stackoverflow.com/a/1005890/6510304 check if it helps.

  • 1

    Virgilio I looked at the links, but I don’t understand what’s wrong. Thanks for the help, I managed to resolve Everson $stmt->bindValue(":{$this->Columns[$i]}",$this->Entity->{'get'. ucfirst($this->Columns[$i])}());

  • But to 'concatenate' in this case would not be the sign of + and yes . (dot).

1 answer

1

You can assemble the method name using the concept of variable functions

<?php
//classe para de teste com get e set
class teste{
  private $nome = "";
  public function getNome(){
   return $this->nome;
    }
  public function setNome($nome){
   $this->nome = $nome ;
   }
}

//criando um objeto para utilizar
$teste = new teste();

//chamando o primeiro método através de um funcção variável
$metodo = "setNome";

//fazendo o teste para verificar se realmente existe...
if(is_callable(array($teste, $metodo))){
  $teste->$metodo("NOME DO FULANO");
}else{
  // trate aqui o erro caso nao exista...
}

// trocando o método
$metodo = "getNome";

if(is_callable(array($teste, $metodo))){
  echo $teste->$metodo();
}else{
  // trate aqui o erro caso nao exista...
}

the result will be

NOME DO FULANO

Browser other questions tagged

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