How to list the properties of an object in php using foreach?

Asked

Viewed 3,129 times

4

I have the following class:

class Usuario{
     private $nome;
     private $profissao;

     function setNome($nome){
         $this->nome = $nome;
     }

     function getNome(){
         return $this->nome;
     }

     function setProfissao($profissao){
         $this->profissao = $profissao;
     }

     function getProfissao(){
         return $this->profissao;
     }
 }

Here I instate an object

$user = new Usuario();

$user->setNome('Nome Qualquer');
$user->setProfissao('Profissão Qualquer');

I wanted to know how I can list all properties of this Objet using foreach. I already know there is get_object_vars that already does it for me. But I wanted to use foreach even for that purpose. Of course the above example is just a simple example.

  • 1

    This answer should help you http://answall.com/a/97571/28595

3 answers

4

You can create a method to list attributes internally, nothing prevents you from using a foreach this way:

class Usuario
{
     private $nome;
     private $profissao;

     public function setNome($nome)
     {
         $this->nome = $nome;
         return $this;
     }

     public function setProfissao($profissao)
     {
         $this->profissao = $profissao;
         return $this;
     }

     public function getNome($nome)
     {
         return $this->nome;
     }

     public function getProfissao($profissao)
     {
         return $this->profissao;
     }

     public function getValueByAttributeName($name)
     {

        if (property_exists($this, $name)) {
           return $this->$name;
        }
     }

    public function getValueByMethodName($name)
    {
        $name = $name.'()';

       if (method_exists($this, $name)) {

           return $this->$name;
       }
    }

    public function getAllAttributes()
    {
        $array = array();

        foreach ($this as $key => $value) {
            if (property_exists($this, $key)) {
                 $array[] = array($key => $value);
            }
         } 
         return $array;

    }
}

$usuario = new Usuario;

$usuario->setNome('Nome Qualquer');
$usuario->setProfissao('Profissão Qualquer');
$data = $usuario->getAllAttributes();

echo 'Exemplo de listar tudo: <pre>';
print_r($data);
echo '</pre><br>Exemplo por método:<br>';
echo '--->'.$usuario->getValueByMethodName('getnome');
echo '<br>';
echo '--->'.$usuario->getValueByMethodName('getprofissao');
echo '<br>Exemplo por atributo:<br>';
echo '--->'.$usuario->getValueByAttributeName('nome');
echo '<br>';
echo '--->'.$usuario->getValueByAttributeName('profissao');

IDEONE

  • When executing the code, in the end, fires a Warning, is that what you expect? see: https://ideone.com/mdUlpm

  • Just a correction I made in my code, in the get methods, the parameter I mistakenly put

  • 2

    @diegofm, the problem was because of the method parentheses, I already changed blz.

4


That would help?

<?php
    class MyClass
    {
        public $var1 = 'value 1';
        public $var2 = 'value 2';
        public $var3 = 'value 3';

        protected $protected = 'protected var';
        private   $private   = 'private var';

        function iterateVisible() {
           echo "MyClass::iterateVisible:\n";
           foreach ($this as $key => $value) {
               print "$key => $value\n";
           }
        }
    }

    $class = new MyClass();

    foreach($class as $key => $value) {
        print "$key => $value\n";
    }
    echo "\n";


    $class->iterateVisible();

    ?>

Source: http://php.net/manual/en/language.oop5.iterations.php

1

In the code you posted, the properties are set to private.

To list these properties would have to create a public method where would then be made such a foreach and the return of the result.

Otherwise it is to use Reflection or Closure Bind.

  • Um... that’s what I was wondering... Out of class isn’t possible then? It would only be if the properties were as public?

  • @Danielomine, even if the attributes are private, the methods are public, so it doesn’t interfere with a listing, you just can’t call them directly.

  • @Dichrist using class, the ideal is always declare methods as public, when they are, example: public function seuMetodo() { ... }.

  • Yes, @Ivanferrer, I thought about it but I preferred to stay focused on what the question says. It says you want to list the properties and not exactly the methods.

  • Yes, I know that. Methods always call public. The only way to use foreach in this situation would be to list attributes within a public method?

  • @Dichrist, by default the methods are public when not specified in the statements. What is your case. But it is bad practice. From PHP5.4 a warning is issued that it is recommended to explicitly declare. Such warning depends on the error log settings.

  • search for hydrate or populate.

Show 2 more comments

Browser other questions tagged

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