Use get_object_vars in a child class

1

I have the following class:

class Dominio {

    private $teste;

    public function getAtributos() {
        return get_object_vars($this);
    }
}

And other classes that inherit it (Domain):

class ClasseQualquer extends Dominio {
    private $outro;
}

I instantiate the class 'AnyQualquery' and call the method 'getAttributes':

$classeQualquer = new ClasseQualquer();
var_export($classeQualquer->getAtributos());

Then it returns the 'test' attribute of the 'Domain' class, but what I need is to get the attributes of the child class in the 'AnyCal' case and get the attribute 'other'.

    
asked by anonymous 28.10.2017 / 05:16

2 answers

1

What worked for me was to use traits, a very interesting feature that I did not know existed in php, but thanks for the strength Wellingthon!

link

I created the file:

<?php

namespace model\dominio;

/**
 * Description of traitDominio
 *
 * @author wictor
 */
trait traitDominio {

    public function getAtributos() {
        return array_keys(get_object_vars($this));
    }

}

And then I imported into my classes:

<?php

namespace model\dominio;

/**
 * Description of Token
 *
 * @author Wictor
 */
class ClasseQualquer extends Dominio {

    use traitDominio;
...
    
10.11.2017 / 18:07
2

You have defined the variables $teste and $outro as being private ( Private ), that is, we can not access from other descendant classes.

In order for the method to work as intended, you should set them to Protected, so they can only be accessed within the class itself or from descendant (inherited) classes.

class Dominio {

    protected $teste = 'Variável teste';
    public function getAtributos() {
        return get_object_vars($this);
    }

}

class ClasseQualquer extends Dominio {
    protected $outro = 'Variável outra';
}

$classeQualquer = new ClasseQualquer();
var_export($classeQualquer->getAtributos());
  

You can see it working at repl.it

    
28.10.2017 / 06:06