How do I compare the property of an object with a string?

Asked

Viewed 65 times

1

class Alunos{

   public $nome; 

}

$aluno= new Alunos();

$aluno->nome="Pedro";

if(propriedade=="nome")

{

   echo $aluno->nome;

}
  • You can give a clearer example?

  • I want to check if the property index in case the public $name is equal to the string "name". I do not want what it contains in name, but rather the content, which is the word name.

  • Explain the purpose because there may be different ways to solve where one can be more suitable than another.

  • The purpose is to write a line in a file, separating by comma. Only in the name that is the first element of the line I n want comma.

1 answer

0

I think what you need is the function property_exists. She returns true if a class or object has a certain property and false otherwise.

class Alunos{

   public $nome; 

}

$aluno= new Alunos();

$aluno->nome="Pedro";

if (property_exists("Alunos", "nome"))
{
   echo $aluno->nome, PHP_EOL; // Pedro
}

Or using the object itself:

if (property_exists($aluno, "nome"))
{
   echo $aluno->nome, PHP_EOL; // Pedro
}

Browser other questions tagged

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