Use get_object_vars in a child class

Asked

Viewed 80 times

1

I got the following class:

class Dominio {

    private $teste;

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

And other classes that inherit it it(Dominio):

class ClasseQualquer extends Dominio {
    private $outro;
}

I urge the class 'Classequalquer' and call the method 'getAtributos':

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

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

2 answers

2

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

In order for the method to work as desired, you must define them as protected ( Protected ), only then can they be accessed within the class itself or from descending classes (inherited).

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 on repl it.

1


What solved for me was to use traits, a very interesting feature that I didn’t know existed in php, but thanks for the Wellingthon force!

http://php.net/manual/en/language.oop5.traits.php

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;
...

Browser other questions tagged

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